Skip to content Skip to sidebar Skip to footer

Listing Variables From External Script Python Without The Built-in And Imported Variables

I'm writing a python script that gets parameters from a json file, opens a template script specified by one of the parameters (from a set of options), and generates a new python sc

Solution 1:

It's kind of unclear what you're trying to do, but from this description you give, this problem might be more easily solved using templates than by generating code entirely from scratch in Python. You might be able to get away with plain old python format strings, or if you need more features jinja2 might be useful.

my_script.py.template

import something

{param1}_variable = 1def {param2}_function():
    something.{something_func}

version_1.json

{
    'param1': 'foo',
    'param2': 'bar',
    'something_func': 'neato_function'
}

Then you generate the output with something like:

template = open('my_script.py.template').read()
with open('my_script_version_1.py', 'w') as f:
    f.write(template.format(**json.load(open('version_1.json'))))

All that being said...are you super sure that you want to do this? Unless there's a specific reason you need to generate a file containing the code, it might be better to use more standard methods (like using regular Python imports)


To actually answer your question: you could try to use the type function on the elements of vars(), but this seems really fragile. Modules will have type <class 'module'>. But then you also have to figure out how to filter out functions, classes, etc.

Post a Comment for "Listing Variables From External Script Python Without The Built-in And Imported Variables"