how can I import [.myfolder.pyfile] as [something else]?

↘锁芯ラ 提交于 2021-02-11 12:47:46

问题


let's say I have

project
   |__ utilities
   |      |__ foo.py
   |
   |__ boost_extensions
   |      |__ myclass.cpp
   |      |__ myclass.so
   |
   |__ someotherstuff
   |      |__ bar.py      
   |
   |__ mylib.py
   |
   |__ __main__.py

Is it possible to do something like this in main.py

import .utilities.foo as Foo
# this function will pass Foo to C++ and initialize it to a global variable
initCppFunction(Foo)

I've tried this but it gives me an invalid syntax error (I'm trying to do this due to some problems with importing python modules from boost/python). Is there a way to do this?

Thanks


回答1:


Use

from .utilities import foo as Foo




回答2:


I think the problem here is that none of these folders have __init__.py in them, either the project folder nor utilities or boost_extensions or someotherstuff.

In order for Python to know that you want to be able to do imports it has to know that there's a whole grouping of code, called a package. You do that by putting __init__.py files wherever you want to formalize and tell Python "this is a bundle of related code".

https://docs.python.org/3/reference/import.html#regular-packages

EDIT

The first answer also makes a good point, that you from x.y import z as the correct syntax.

EDIT 2

Krishnan is completely right. The __init__.py files don't need to have anything in them. You can put code in them if you want, but it's not required at all.



来源:https://stackoverflow.com/questions/63061583/how-can-i-import-myfolder-pyfile-as-something-else

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