简体   繁体   中英

Importing a package into all modules in a directory

What is the most canonical way to import a package into multiple files? Is the best way to import into a common module and then import that, or is there a way to do it somewhere like __init__.py?

This is the repetition I'm trying to avoid:

file1.py

from typing import NoReturn
...

file2.py

from typing import NoReturn
...

file3.py

from typing import NoReturn
...

Practically no. The NoReturn or whatsoever must be imported from somewhere.

You could "inject" an attribute to a module from "outside" like this:

# this is __init__py

from typing import NoReturn

from . import file1
from . import file2

file1.NoReturn = file2.NoReturn = NoReturn

but:

  • it's an ugly hack,
  • the attribute is added after the import, so it is of limited use:

ie

# this is file1.py

def func() -> NoReturn:   # will fail, NoReturn undefined at import time
    raise ...

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