'I know eval() is bad practice; is there an alternative for my code which involves getting the __doc__ of all funcs in all files in a folder?
I'm making a project which involves importing a directory as a module (it has an __init__.py) then iterating through all files in that directory and printing the docstring of all the functions in each file.
This is my main.py code, in which I have to use eval() to convert the file name from a string to an actual file object.
import fruits
from fruits import *
docs = []
for file in fruits.__all__:
tmp = []
for name, object in vars(eval(file)).items():
if callable(object):
tmp.append(object.__doc__)
docs.append(tmp)
And here is my __init__.py:
from os.path import dirname, basename, isfile, join
import glob
fruits = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [basename(f)[:-3] for f in fruits if isfile(f) and not f.endswith("__init__.py")]
The contents of fruits/ is a few files named things like apple.py and orange.py that each have a few functions that just print "hello" and have a docstring consisting of their name.
I know I could do the main.py more efficiently with list comprehension; but i'm just playing around and testing it at this stage.
I would rather not have to use eval() so if you know of an alternative way to accomplish this I would be very grateful.
Thank you
Solution 1:[1]
Your variables should be accessible in globals() so you can just
for name, object in vars(globals()[file]).items():
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lejlot |
