Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using methods defined in __init__.py within the module

Tags:

python

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?

like image 848
user1649891 Avatar asked Sep 05 '12 18:09

user1649891


2 Answers

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.

like image 138
Julian Avatar answered Oct 26 '22 23:10

Julian


Use relative imports:

from . import win, lose
like image 25
Andreas Jung Avatar answered Oct 27 '22 00:10

Andreas Jung