Home > Software design >  Smart way to load a local python module with a class instance?
Smart way to load a local python module with a class instance?

Time:01-21

What is a smart way to load a local python file with a python class instance so that all variables defined in that python file gets added to the class's attributes?

CodePudding user response:

With a file vars.py containing:

x = 2
y = 'fish'
for i in range(4):
    x = x * 3

Then load x and y into a class in 2 ways:

Using __import__()

Note: This will stuff all the globals from your module into the class. A lot of junk. Also the imported name has to be a package, not just a single file.

class DangerZone:
    def load_attrs(self, fn):
        _vars = __import__(fn)
        for attr_name, attr_val in _vars.items():
            self.__dict__[attr_name] = attr_val

Using exec()

Ok this is dangerous (using exec() to run arbitrary code from outside), but here goes.

class DangerZone:
    def load_attrs(self, fn):
        _globals = {}
        _locals = {}
        exec(open(fn).read(), _globals, _locals)
        for attr_name, attr_val in _locals.items():
            self.__dict__[attr_name] = attr_val

Result:

dz = DangerZone()
dz.load_attrs('vars.py')
print(dz.x, dz.y)

Prints:

162 fish
  •  Tags:  
  • Related