Importing methods from a Python package

时间:2017-04-06 16:45:17

标签: python python-3.x

I'm having an issue importing all methods from a file so that I can use it as a package. I have the following:

myapp.py
mypackage/
mypackage/__init__.py
mypackage/mypackage.py

Inside of mypackage.py I have method1() and method2(). Inside of myapp.py I want to do this:

import mypackage
mypackage.method1()

However this doesn't work. Instead I need to do mypackage.mypackage.method1() and I'm not sure what to do to fix that. The only way I found was to delete __init__.py and rename mypackage.py to __init__.py which doesn't seem right.

What do I need to put in the init file to import all methods so I don't have to always type the package name twice?

1 个答案:

答案 0 :(得分:0)

In your example you have a mypackage package (a directory with an __init__.py) and a mypackage module in that package. You've just posted a strawman example of course, but you risk making import mistakes if you name a module the same as your package. And calling non-package things "package" is certainly confusing!

To get the methods from mypackage.py into mypackage, you can do package-relative imports in mypackage/__init__.py:

from .mypackage import method1, method2

...or

from .mypackage import *

The reason you should rename mypackage.py to something else is that a small mistake like missing that dot causes the wrong thing to be imported.