When I try to import a module in python(.py file) it gives a syntax error. The module name starts with a numeral. Is that the reason for the syntax error?
Asked
Active
Viewed 5,788 times
1
-
Your question is already solved here. [http://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number](http://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number) You can do `theModule = __import__('123theModuleName')` here instead of `import 123theModuleName` And, you should not import modules including the suffix ".py" as well, but I guess you already knew that. – albusshin May 20 '13 at 07:06
-
I tried the above code but it still says "NameError: name '_import_' is not defined". – user2400748 May 20 '13 at 10:51
-
You should add two underscores on both side of `import`, thus made it `__import__` – albusshin May 20 '13 at 11:03
2 Answers
6
Yes, that is the reason for the syntax error. There are various ways of importing it anyway, but it's better to rename the module.
The reason is that variable names can't start with a numeral. Hence you can't do
import 123foo
or even
123foo = __import__('123foo')
They are both syntax errors. You can do
foo123 = __import__('123foo')
But it's better to just rename the module to foo123 and import it normally instead.

Lennart Regebro
- 167,292
- 41
- 224
- 251
3
Yes. To avoid this, you can do __import__("number")
. For example:
mymodule = __import__("1234")
Which would be the same as:
import 1234 as mymodule
Without the SyntaxError
, of course.
You can read more about it here.