Python Forum
Importing packages with long names
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Importing packages with long names
#6
What i do is to lift sub modules and bind package together,so can have one simple main import.
This can all be done in top level __init__.py .
This avoid long import statement and can make package easier to use for end users.
Example:
mod_pack\
|-- __init__.py
|-- my_extension_first.py
  my_extension_second\ 
    |-- my_extension_code.py

# __init__.py
from .my_extension_first import first
from .my_extension_second.my_extension_code import second
# my_extension_first.py
def first():
    return 'Now in first extension code'
# my_extension_code.py
def second():
    return 'Now in second extension code'
Test package:
>>> import mod_pack

>>> mod_pack.first()
'Now in first extension code'

>>> mod_pack.second()
'Now in second extension code'
Or:
>>> from mod_pack import first, second

>>> first()
'Now in first extension code'
>>> second()
'Now in second extension code'
This also work,but don't need your uses to navigate your whole tree to get to code Wink
>>> import mod_pack 

>>> mod_pack.my_extension_second.my_extension_code.second()
'Now in second extension code'
Other examples in these post1, post2.

See that i only use one __init__.py
From Python 3.3+ supports Implicit Namespace Packages that allows to create a package without an __init__.py file.
This however only applies to empty __init__.py files.
So empty __init__.py files are no longer necessary and can be omitted.
Reply


Messages In This Thread
Importing packages with long names - by joel_graff - Nov-06-2019, 01:01 PM
RE: Importing packages with long names - by snippsat - Nov-07-2019, 11:14 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020