How to import a module but ignoring the package's __init__.py?

时间秒杀一切 提交于 2021-02-07 14:18:57

问题


I'm trying to import a function which is in a module inside a package in Python, but when I try:

from package.module import some_function

Python executes the package's _init_.py but it can't happen.

Is there a way to import the function telling Python to ignore the package's _init_.py?


回答1:


The answer is No, you can't import a python package without the __init__.py being executed. By definition, to make a package, you must put in that directory a __init__.py.

But, you can make an empty __init__.py file.

If you want just to import a function from a module, you can use:

import sys
sys.path.append('path_to_package/')

from module import some_function

Note that this is a dirty solution, and won't always work.



来源:https://stackoverflow.com/questions/13763985/how-to-import-a-module-but-ignoring-the-packages-init-py

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