I have a module that defines a class and a function:
#barbaz.py
class Bar:
pass
def baz():
return "hello"
In another module, I have a function with an eval statement:
#foo.py (version 1)
def foo(baz: callable):
bazstr: str = baz.__name__
print(bazstr)
try:
f=eval(f'{bazstr}()')
print(f'result: {f}')
except Exception as e:
print(f"eval error: {e}")
And finally, I have a test in another module:
#test.py
from evalf import foo
from barbaz import baz, Bar
#This works...
foo(baz)
#This doesn't
foo(Bar)
The baz
works, but the Bar
doesn't. I get the output:
baz
result: hello
Bar
eval error: name 'Bar' is not defined
It seems that eval
cannot use classes that have been imported from a module, unless it is imported directly into the same module as the foo()
function. i.e, this works:
#foo.py (version 2)
from barbaz import Bar
def foo(baz: callable):
bazstr: str = baz.__name__
print(bazstr)
try:
f=eval(f'{bazstr}()')
print(f'result: {f}')
except Exception as e:
print(f"eval error: {e}")
foo(Bar)
Why does version 2 of foo.py
work, and version 1 thrown the shown error?
How can I get around this, and use an imported class in an eval statement that lives in it's own module?