python string to symbolic name
I want to check imported names.
Code:import fst # empty file fst.py
for s in dir(fst):
print(s) # got string with symbolic names
Output:
__builtins__
__cached__
__doc__
__file__
__name__
__package__
Now I want to check values of each defined name:
Code:print(__builtins__)
print(__cached__)
print(__doc__)
print(__file__)
print(__name__)
print(__package__)
Question: How can I "extract" symbolic name from string?
supposed code:import fst #empty file fst.py
for s i开发者_如何转开发n dir(fst):
print(s, StrToSym(s)) # this call should be equal to str("__name__", __name__)
Use getattr
:
for s in dir(fst):
print (getattr(fst, s))
Use the getattr
function:
print(s, getattr(fst, s))
There's no such thing as a "symbolic name". What module contains is available as its attributes, so getattr(module, name)
is what you're looking for.
精彩评论