I have a script "7update.py" and would like to import it. Is there any way to do this? I can't just type import 7update
because it starts with a number so it's not a valid identifier. I've tried using import('7update')
but that doesn't work.
Asked
Active
Viewed 527 times
2

Jason S
- 184,598
- 164
- 608
- 970
-
1Very similar question [here](http://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number) -- well, it's "8puzzle" instead of "7update".. – DSM Mar 14 '12 at 15:39
-
Learnt something thanks to your question, +1. – Eduardo Ivanec Mar 14 '12 at 15:40
-
Why would you be in such a situation? – Mike Graham Mar 14 '12 at 15:45
3 Answers
4
You can, but you have to refer to it by a valid identifier, like that:
__import__('7update')
sevenupdate = sys.modules['7update']

yachoor
- 929
- 1
- 8
- 18
4
seven_up = __import__("7update")
Where seven_up
is valid identifier you're going to be using in your python code for that module.

vartec
- 131,205
- 36
- 218
- 244
1
Here is an example from the docs:
import imp
import sys
def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
except KeyError:
pass
# If any of the following calls raises an exception,
# there's a problem we can't handle -- let the caller handle it.
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()

Marcin
- 48,559
- 18
- 128
- 201