0

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
binit92
  • 75
  • 15

2 Answers2

5

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
3

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:

  1. They start with a letter or underscore.
  2. After that, they are composed entirely of letters, numbers, and underscores.
  3. They are lowercase.
  4. They are short (nobody likes a huge name to import).

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.

  • +1 for the first part. – Games Brainiac Nov 30 '13 at 16:43
  • Yes, and downvote for even mentioning the second part to a novice user. – Lukas Graf Nov 30 '13 at 16:44
  • Well, removed the downvote after you added the disclaimer. Still, the topic here should be naming rules (why is `8` an invalid name?), not import trickery. – Lukas Graf Nov 30 '13 at 16:49
  • 1
    @LukasGraf - There. I added a huge disclaimer and also linked to the PEP docs. I gave the newbie all of the bubblewrap I could. :) –  Nov 30 '13 at 17:01
  • 1
    @iCodez Much better. However, identifiers not starting with a number is not just a convention encouraged by PEP8, it's a requirement defined in the [lanuage grammar](http://docs.python.org/2/reference/lexical_analysis.html#identifiers). So by absuing `__import__` to still import such a module is something that just shouldn't be done, even by someone who knows what he's doing. `__import__` has its legitimate uses (dynamically importing modules by name for example), but this is not one of them in my opinion. – Lukas Graf Nov 30 '13 at 17:57