python - Importing classes from different files in a subdirectory -
here's structure i'm working with:
directory/ script.py subdir/ __init__.py myclass01.py myclass02.py what want import in script.py classes defined in myclass01.py , myclass02.py. if do:
from subdir.myclass01 import * it works fine class defined in myclass01.py. solution if there many classes defined in different files in subdir , want import of them, i'd have type 1 line each file. there must shortcut this. tried:
from subdir.* import * but didn't work out.
edit: here contents of files:
this __init__.py (using __all__ apalala suggested):
__all__ = ['myclass01','myclass02'] this myclass01.py:
class myclass01: def printsomething(): print 'hey' this myclass02.py:
class myclass02: def printsomething(): print 'sup' this script.py:
from subdir import * myclass01().printsomething() myclass02().printsomething() this traceback when try run script.py:
file "script.py", line 1, in <module> subdir import * attributeerror: 'module' object has no attribute 'myclass01'
although names used there different what's shown in question's directory structure, use answer question titled namespacing , classes. __init__.py shown there have allowed usepackage.py script have been written way (package maps subdir in question, , class1 myclass01, etc):
from package import * print class1 print class2 print class3 revision (updated):
oops, sorry, code in other answer doesn't quite want — automatically imports names of package submodules. make import named attributes each submodule requires few more lines of code. here's modified version of package's __init__.py file (which works in python 3.4.1):
def _import_package_files(): """ dynamically import public attributes of python modules in file's directory (the package directory) , return list of names. """ import os exports = [] globals_, locals_ = globals(), locals() package_path = os.path.dirname(__file__) package_name = os.path.basename(package_path) filename in os.listdir(package_path): modulename, ext = os.path.splitext(filename) if modulename[0] != '_' , ext in ('.py', '.pyw'): subpackage = '{}.{}'.format(package_name, modulename) # pkg relative module = __import__(subpackage, globals_, locals_, [modulename]) modict = module.__dict__ names = (modict['__all__'] if '__all__' in modict else [name name in modict if name[0] != '_']) # public exports.extend(names) globals_.update((name, modict[name]) name in names) return exports if __name__ != '__main__': __all__ = ['__all__'] + _import_package_files() # '__all__' in __all__ alternatively can put above separate .py module file of own in package directory, , use package's __init__.py this:
if __name__ != '__main__': ._import_package_files import * # defines __all__ __all__.remove('__all__') # prevent export (optional) whatever name file, should starts _ underscore character doesn't try import recursively.
Comments
Post a Comment