I am using python 2.7. I have a folder with a number of .py files in it that define functions, load objects, etc. that I would like to use in my main script. I want to accomplish the following two objectives:
- Load all objects from all .py files in this directory, without knowing the file names in advance.
- Access these objects in my main script without prefixing, e.g. without needing to use
filename.function_name()
I understand that this does not conform to accepted best practices for python modules. Nevertheless:
I am writing code purely for my own use. It will never be shared with or used by others.
In the course of my development work, I frequently change the names of files, move object definitions from one file to another, etc. Thus, it is cumbersome to need to go to my main script and change the names of the function name prefixes each time I do this.
I am an adult. I understand the concept of risks from name conflicts. I employ my own naming conventions with functions and objects I create to ensure they won't conflict with other names.
My first shot at this was to just loop through the files in the directory using os.listdir()
and then call execfile()
on those. When this did not work, I reviewed the responses here: Loading all modules in a folder in Python . I found many helpful things, but none get me quite where I want. Specifically, if include in my __init__.py
file the response here:
from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f)]
and then use in my main script:
os.chdir("/path/to/dir/") # folder that contains `Module_Dir`
from Module_Dir import *
then I can gain access to all of the objects defined in the files in my directory without needing to know the names of those files ahead of time (thus satisfying #1 from my objectives). But, this still requires me to call upon those functions and objects using filename.function_name()
, etc. Likewise, if I include in my __init__.py
file explicitly:
from filename1 import *
from filename2 import *
etc.
Then I can use in my main script the same from Module_Dir import *
as above. Now, I get access to my objects without the prefixes, but it requires me to specify explicitly the names of the files in __init__.py
.
Is there a solution that can combine these two, thus accomplishing both of my objectives? I also tried (as suggested here, for instance, including the following in __init__.py
:
import os
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
__import__(module[:-3], locals(), globals())
del module
But again, this still required the name prefixing. I tried to see if there were optional arguments or modifications to how I use __import__
here, or applications using python 2.7's importlib, but did not make progress on either front.