2

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.

Jason S
  • 184,598
  • 164
  • 608
  • 970

3 Answers3

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