How to import module when module name has a '-' dash or hyphen in it? How to import module when module name has a '-' dash or hyphen in it? python python

How to import module when module name has a '-' dash or hyphen in it?


Starting from Python 3.1, you can use importlib :

import importlib  foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )


you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.pybaz = 'quux'
>>> execfile('foo-bar.py')>>> baz'quux'>>> 


If you can't rename the module to match Python naming conventions, create a new module to act as an intermediary:

 ---- foo_proxy.py ---- tmp = __import__('foo-bar') globals().update(vars(tmp)) ---- main.py ---- from foo_proxy import * 


matomo