Suppose I have the following directory structure:
lib\
--__init__.py
--foo.py
--bar.py
Inside foo and bar, there are seperate methods that both need the same method. For instance:
foo:
def method1():
win()
bar:
def method2(number):
if number < 0:
lose()
else:
win()
__init__:
def win():
print "You Win!"
def lose():
print "You Lose...."
Is there a way to use the win and lose methods within the init.py in the modules respective subfiles, or do I have to create another file within the folder and have foo and bar import that?
Yes, just import the __init__.py
module (via either an absolute or relative import, it doesn't really matter).
I never like relative imports, so I'd do so with import mypackage
in mypackage.foo
, which imports the __init__.py
just like a relative import does, and then using it there. I also don't like putting anything in __init__.py
though generally, so perhaps you should consider the shared common file anyhow.
Use relative imports:
from . import win, lose
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With