Python: import function from an already imported module

允我心安 提交于 2021-01-29 01:41:13

问题


Suppose I have a python package my_package which contains a module my_module which contains a function my_function.

I was trying to do the following import in python interactive shell:

>>> from my_package import my_module
>>> my_module.my_function()            # => OK
>>> from my_module import my_function  # => ImportError: No module named my_module
>>> from my_package.my_module import my_function   # => OK

I am quite surprised at the ImportError at the third line above: since the my_module is already imported, why can I not import a function from it? Maybe I have some miss understanding on how python import system works, and any clarification will be highly appreciated!


Here is the directory structure and source code.

my_package
  |- __init__.py
  |- my_module.py

Here is the __init__.py file

all = ["my_module"]

and here is the my_module.py file

def my_function():
    pass

回答1:


The Python import system just doesn't work that way. When you do from foo import bar, foo has to be a "real", fully-qualified package or module name (or a relative one using dots). That is, it has to be something that you could use in a plain import foo. It can't just be a module object you have lying around. For instance, you also can't do this:

import foo as bar
from bar import someFunction

This is stated in the documentation, although you have to read through that section to get the full picture. It says:

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The statement comes in two forms differing on whether it uses the from keyword. The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly.

Step (1) is "finding the module", and if you read on you will see that this is the process where it looks in sys.modules, sys.path, etc. There is no point at which it looks for a name in the importing namespace that happens to have a module object as its value. Note that the module-finding process is no different for the two kinds of imports; the way it finds foo when you do import foo is the same way it finds it when you do from foo import bar. If a plain import my_module would not work (as in your example), then from my_module import stuff won't work either.

Note that if you already imported the module and just want a shorter name for a function inside it, you can just assign a regular variable to the function:

from my_package import my_module
myfunc = my_module.my_function


来源:https://stackoverflow.com/questions/27830262/python-import-function-from-an-already-imported-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!