I have hello() in test/abc.py as shown below:
# "test/abc.py"
def hello():
return "Hello"
Then, I import and call hello() from abc.py in test/main.py as shown below:
# "test/main.py"
from abc import hello
print(hello())
But, I got the error below:
ImportError: cannot import name 'hello' from 'abc'
So, I import abc.py and call abc.hello() in test/main.py as shown below:
# "test/main.py"
import abc
print(abc.hello())
But, I got another error below:
AttributeError: module 'abc' has no attribute 'hello'
Actually, I can import abc.py without error as shown below:
import abc
# print(abc.hello())
So, how can I import and call hello() from abc.py?
Actually, you import the built-in module abc which means Abstract Base Classes to create abstract classes so don't create the file with the name
abc.py. *You can see all built-in modules in Python Module Index which you cannot use as file names.So, you should change
abc.pyto other name such asgreeting.pyas shown below:Then, both work without error as shown below:
In addition, importing
def.pybelow getsSyntaxError: invalid syntaxerror becausedefis a reserved word to define functions. *You can see all reserved words in 2.3.1 Keywords and don't useabcdef'sabcanddefas file names: