Pure Python Equivalent to...

The following examples show how to replace common 3rd-party pip packages with “pure” Python using only the standard library. This does not mean the packages are bad, on the contrary, they are all high quality and you should use them. However there are a few situations where you might want to replace a 3rd-party package with your own code:

Table of Contents

Missing an example? Contribute on GitHub!

Jinja Templates (Simple)

Jinja2 is an amazing template renderer. It is capable of generating huge complicated web pages, system configuration files, or just about anything else you throw at it. It is also endlessly customizable via plugins and extensions.

However, if you just need to render a simple template, such as an email or a config file, you could easily do that using Python's built-in string formatting functionality.

In either case, you would probably want to read the templates from a file, and write the outputs to another file using Python's open() command.

Before...

from jinja2 import Template


# Values.
name = "Monty"
num = 4

# Jinja template language syntax.
simple_tmpl = """
Hello {{name}},
Your magic number is {{num}}.
"""

# Render template with Jinja using values.
template = Template(simple_tmpl)
output = template.render(name=name, num=num)

print(output)

With the Python standard library...

# Values.
name = "Monty"
num = 4

# Python string format syntax.
simple_tmpl = """
Hello {name},
Your magic number is {num}.
"""

# Render template with Python string formatter.
output = simple_tmpl.format(name=name, num=num)

print(output)

Jinja Templates (Advanced)

Building on the simpler Jinja example above, we will now add for loops to our templates. If you need this kind of functionality, you should probably be using Jinja, but below is an example of how one might write a simple for loop parser using Python's built-in string formatting functionality.

Before...

from jinja2 import Template


# Values.
name = "Monty"
order = [
    {"qty": 1, "name": "Widget"},
    {"qty": 3, "name": "Carpets"}
]

# Jinja template language stynax.
fancy_tmpl = """
Hello {{name}},
You ordered:
{%- for item in order %}
* {{item.qty}} x {{item.name}}
{%- endfor %}
Thank you.
"""

# Render template with Jinja using values.
template = Template(fancy_tmpl)
output = template.render(
    {"name": name, "order": order}
)

print(output)

With the Python standard library...

# Values.
name = "Monty"
order = [
    {"qty": 1, "name": "Widget"},
    {"qty": 3, "name": "Carpets"}
]

# Our home-grown template language, based on
# Python's string format syntax.
fancy_templ = """
Hello {name},
You ordered:
{{ for item in order }}
* {item[qty]} x {item[name]}
{{ endfor }}
Thank you.
"""


def format_template(template: str, values: dict) -> str:
    """
    Function to process `for` loops in our own simple
    template language. Use for loops as so:
        {{ for item in list }}
        ...
        {{ endfor }}
    """
    loop = ""
    loop_elem = ""
    loop_iter = ""
    in_loop = False
    output = ""
    for line in template.splitlines(keepends=True):
        # Check if starting a loop.
        if line.strip().startswith(r"{{ for"):
            in_loop = True
            # Strip spaces and braces, and parse the `for` statement.
            parsed = line.strip("}{ \t\r\n").lstrip("for").split("in")
            loop_elem = parsed[0].strip()
            loop_iter = parsed[1].strip()
            continue

        # Check if done with a loop.
        if line.strip().startswith(r"{{ endfor }}"):
            # Render the contents of the loop now.
            for x in values[loop_iter]:
                output += loop.format(**{loop_elem: x})
            # Reset and then exit the loop.
            in_loop = False
            loop = ""
            continue

        # Format the current line or load it into a loop.
        if in_loop:
            loop += line
        else:
            output += line.format(**values)

    return output


# Render template with our custom function.
output = format_template(
    fancy_templ,
    {"name": name, "order": order}
)

print(output)