How do I import from a file in the current directory in Python 3?

久未见 提交于 2019-12-13 20:26:03

问题


In python 2 I can create a module like this:

parent
->module
  ->__init__.py (init calls 'from file import ClassName')
    file.py
    ->class ClassName(obj)

And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:

"""__init__.py"""
from file import ClassName

"""file.py"""
class ClassName(object): ...etc etc

I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?


回答1:


In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.

Absolute import:

from parent.file import ClassName

Relative import:

from . file import ClassName
# look for the module file in same directory as the current module



回答2:


Try import it this way:

from .file import ClassName

See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.



来源:https://stackoverflow.com/questions/57213543/grpc-generated-python-script-fails-to-find-a-local-module-in-the-same-directory

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