python - Dynamically instantiating objects -
i'm attempting instantiate object string. specifically, i'm trying change this:
from node.mapper import mapper mapper = mapper(file) mapper.map(src, dst) into this:
with open('c:.../node/mapper.py', 'r') f: mapping_script = f.read() eval(mapping_script) mapper = mapper(file) mapper.map(src, dst) the motivation seemingly bizarre task able store different versions of mapping scripts in database , retrieve/use them needed (with emphasis on polymorphism of map() method).
the above not work. reason, eval() throws syntaxerror: invalid syntax. don't understand since it's same file that's being imported in first case. there reason why eval() cannot used define classes?
i should note aware of security concerns around eval(). love hear of alternative approaches if there any. other thing can think of fetch script, physically save node package directory, , import it, seems crazier.
you need use exec:
exec(mapping_script) eval() works expressions. exec() works statements. typical python script contains statements.
for example:
code = """class mapper: pass""" exec(code) mapper = mapper() print(mapper) output:
<__main__.mapper object @ 0x10ae326a0> make sure either call exec() (python 3, in python 2 statement) @ module level. when call in function, need add globals(), example exec(code, globals()), make objects available in global scope , rest of function discussed here.
Comments
Post a Comment