简体   繁体   中英

Python Import system, importing function from a module that imports the same function from another package

Came across code with following structure:

/root
  /app
    __init__.py
    mod1.py
    mod2.py
  /lib
    __init__.py
    libmod.py

mod1:

from lib.libmod import somefunc

mod2:

from app.mod1 import somefunc

While there are no runtime errors with this, my gut tells me that mod2 should import somefunc from lib. I have limited understanding of the python import system, but I`m concered about importing imports/code running twice or doing some kind of polution of namespaces.Should I be concerned at all, or is this perfectly fine Python?

This is perfectly fine. The from x import name statement merely imports name from x – it does not care where name was initially defined.

In fact, the standard library itself frequently re-exports names from internal or C modules.

# collections/abc.py
from _collections_abc import *
from _collections_abc import __all__
from _collections_abc import _CallableGenericAlias

Re-exporting names can help make the public appearance of a package simpler to use, while giving complete freedom to how the implementation is structured.

However, one should be careful when re-exporting names across packages. Just because a package exposes a name today does not mean that a future version does so as well. When the intermediate package is not under your control, avoid making assumptions and prefer importing from the official source.

# bad: import undocumented attribute
from subprocess import os
# good: import with official name
import os

The notion of "where" an object was defined does not generally make sense. For example, consider defining a module for literal constants:

# constants.py
MIDNIGHT = 0
NOON = 12 

There is a single value for every 0 and 12 throughout the entire application . The statement from constants import MIDNIGHT, NOON has no way of checking where the objects were defined initially.

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