Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

Your variables should be accessible in globals() so you can just

    for name, object in vars(globals()[file]).items():
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading