17

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?

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

There are clear reasons for using relative imports, with maintainability being the primary one. See PEP 328. (I agree with the advice to keep __init__.py as empty as possible, though.)
I'm aware of the reasons there, I just don't think they're good (or outweigh the reasons for absolute imports) :).
7

Use relative imports:

from . import win, lose

4 Comments

Relative imports are not really the point here, the point is just that you need to import __init__.py, however you'd like to do so.
Julian, easel solution works. from . import win, lose imports "win" and "lose" from ".", which is the current package = __init__.py.
@Bakuriu of course it works, I just said it's not really the point here, the point is just to import the module containing the functions -- how you do so is up to you :).
Ah okay. I misunderstood your comment. Next time I'll read twice before replying :s By the way, I, instead, like relative imports... de gustibus non est disputandum :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.