methods - python can't use function in submodule -
my folder structure this:
pythonstuff/ program.py modulea/ __init__.py foo.py bar.py
here's code bar.py
:
def hello(): print("hello, world!")
here's code program.py
:
#!/usr/bin/env python3 modulea import bar bar.hello()
i run $ python3 program.py
somehow error:
file "program.py", line 3, in <module> bar.hello() attributeerror: 'module' object has no attribute 'hello'
edit: __init__.py
file empty.
edit2: after trying realized had bar.py
in root directory contained hello()
method. bar.py
in modulea/
directory empty.
add it
import os __all__ = [] module in os.listdir(os.path.dirname(__file__)): if module != '__init__.py' , module[-3:] == '.py': __all__.append(module[:-3])
the init.py files required make python treat directories containing packages; done prevent directories common name, such string, unintentionally hiding valid modules occur later on module search path. in simplest case, init.py can empty file, can execute initialization code package or set all variable, described later.
from documentation
so code you're explicitly adding modules in modulea variable. this explains variable
Comments
Post a Comment