Search code examples
pythonpython-2.7flaskflask-principal

Add attributes to Python module at runtime to be imported later


I'm adding attributes to a module at runtime using the following inside a loop:

this_module = sys.modules[__name__]
setattr(this_module, attr_name, attr_value)

When I call print dir(this_module) from the module, it shows the attributes. Great!

When I import the module and try to use the attribute in a decorator, an AttributeError exception keeps getting thrown. To debug, I called dir() on the imported module and none of the attributes added on the fly are listed!

I even added the attribute names to __all__ for the import * and still nothing!

Any ideas would be great. Also, please let me know of any terminology I could be missing. I wasn't able to find an answer searching Google.

--

Per a suggestion by Kevin, I added a dictionary to my Flask application (instead of his suggestion of top-level, just for ease of testing) and added those attributes to it:

app.security = dict()

In the loop:

app.security[attr_name] = attr_value

In the module where the decorator is used ('time_entry' is an attribute name and it holds a class instance):

@app.security['time_entry'].need()

When I try to start the server, I now get this error:

    @security["time_write"].require()
             ^
    SyntaxError: invalid syntax

Solution

  • I've created a workaround for my particular problem. It's not a solution and I still plan on investigating it further once this project is finished.

    I created a dummy class and then set an attribute with an instance of it in my Flask application.

    class Security: pass
    app.security = Security()
    

    Then, I set the attributes directly to the Security class:

    setattr(app.security, attr_name, attr_value)
    

    Again, it doesn't resolve why those module-level attributes I was creating at runtime weren't being imported. I'll come back and edit this once I have the answer to that question.