Is there something that automatically writes code for us?

Select one to make it a common component

Choose binary templates to generate code

Option 3 let me know in the comments 🙂

There is a templatingengine in Python called Jinja2, but it is usually seen as an introduction to generating HTML templates. It can generate any UTF-8 code.

How do you make it?

# Code generator
from jinja2 import Template

# Mister becomes a word

tmpl = '{{ name }}'  # template
tmp = Template(tmpl)  # load template
result = tmp.render(name='mikele')  # Input variables to generate results
print(result)  # mikele
Copy the code

Define the above functions as functions

def render(tmpl, *args, **kwds):
    '''jinja2 render'''
    vars = dict(*args, **kwds)
    tmp = Template(tmpl)
    return tmp.render(vars).strip()
Copy the code

Generate a list loop

fruits = ['apple'.'banana']

tmpl_list = """
{% for fruit in fruits %}
{{ fruit }}
{% endfor %}
"""

result = render(tmpl_list, fruits=fruits)
print(result)
Copy the code

apple

banana

Add a – before % to get rid of the newline character

tmpl_list = """
{% for fruit in fruits -%}
{{ loop.index }}. {{ fruit }}
{% endfor %}
"""

print(render(tmpl_list, fruits=fruits))
Copy the code
  1. apple
  2. banana

Generate a function

tmpl_fun = """ def {{fun}}(): pass """

print(render(tmpl_fun, fun='eat'))
Copy the code
# the results
def eat():
    pass
Copy the code

The generated classes

tmpl_class = """ class {{ model }}s: pass """

print(render(tmpl_class, model='Blog'))
Copy the code
class Blogs:
    pass
Copy the code

Import modules, classes…

tmpl_import = """
from person import {{ models|join(', ') }}
"""

print(render(tmpl_import, models=['Teacher'.'Student']))
Copy the code

from person import Teacher, Student

judge

tmpl_if = "" "{% if a > 2%} {{a}}} else {% % # is less than 2 {% endif %} "" "

print(render(tmpl_if, a=3))
Copy the code

Save the code to the programcodes.py

def save(data, filename='codes.py'):
    with open(filename, 'w') as f:
        f.write(data)
        
save(data=result)
Copy the code

With these you can combine them to automatically generate a program.

If there are few variables, use a template file. If several templates are to be spelled together, define template variables directly like this. Redefine variables.

For the moment…

For more information, please visit Jinja2 official website for Jinja2 template

If you have any questions, please leave a message or send me email.