0

Suppose I create a module on the fly:

import imp
my_module = imp.new_module('my_module')

and I want to add n similar names/value to this module, something that would be equivalent to

my_module.a1 = None
my_module.a2 = None
my_module.a3 = None
...

How can I access a module namespace like a dictionary (or in a similar way) so that I can write something like

for i in range(n):
    my_module.some_env_like_dict[f"a{i}"] = None

Also how can I remove these names in a similar way?

I understand that Python may not have a recommended or official way of doing this. Obviously this is not for any serious project.

I'm looking for a solution that is more elegant than using exec.

Loax
  • 615
  • 5
  • 11

1 Answers1

1

I think what you're doing is essentially correct, with just a few additions:

my_module = imp.new_module('my_module')
my_module.var1 = 123

This creates a module, and sets var1 to 123 within the module. You can access it as my_module.var1 just as you would for any other module.

To access the attributes from strings, you can do:

val = getattr(my_module, "var1")
setattr(my_module, "var1", val + 1)

This sets val to 123, then updates var1 in my_module with the value 124. You can also add new attributes to the module in this manner.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41