I have a function ispalindrome in file named 8.py
how to import it ?
why 8 is invalid name if I can make a .py file with this name
from 8 import ispalindrome
I have a function ispalindrome in file named 8.py
how to import it ?
why 8 is invalid name if I can make a .py file with this name
from 8 import ispalindrome
Python module names have to be valid identifiers. "8" is not a valid identifier. Try "eight" or "file8" or anything that does not start with a number.
Best answer: rename your file. ;)
Having a file named 8.py
breaks the naming convention for files as well as Python's language grammar (your trouble importing it makes it clear why these rules are in place).
Generally, you should make filenames the same as variables:
However, if you must name the file 8.py
, you can use __import__
to import it.
To demonstrate, I made a simple 8.py
file that had the following function:
def func():
return True
Here is the test I ran:
>>> from 8 import func
File "<stdin>", line 1
from 8 import func
^
SyntaxError: invalid syntax
>>> x = __import__("8")
>>> x.func()
True
>>>
As you can see, using __import__
works. However, it is considered sloppy and should generally be avoided. I strongly recommended that you heed my first answer and rename the file if you can.