简体   繁体   中英

How can I convince Python to import a class from a submodule when you import the package?

Example: mypkg/submodule.py with class MyClass inside.

I want to be able to do:

import mypkg
obj = MyClass()

What I need to do in order to make this work with default import?

I note that from pkg import * and import pkg.submodule works are working but I want to change the behaviour of the default import .

This is clearly related to __init__.py and __all__ .

You can't do that normally (I guess with some crazy hacks it could be possible). You either have:

from mypkg.submodule import MyClass

Or if you setup __init__.py in the package appropriately, you could have:

from mypkg import MyClass

It is not possible, a simple python import will only add the module to the current namespace.

Now there are 3 alternatives for importing MyClass :

# mypkg/__init__.py
from submodule import MyClass
__all__ = ["MyClass"]

# mypkg/submodule.py
def MyClass(obj):
    pass

# test-usage.py
import mypkg
mypkg.MyClass()

# test-usage-2.py
from mypkg import MyClass
MyClass()

# test-usage-3.py
from mypkg import *
MyClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM