How to import a module when there is a "-" dash or hyphen in the module name?

I want to import foo-bar.py. It works:

foobar = __import__("foo-bar") 

It does not mean:

 from "foo-bar" import * 

My question is: Is it possible to use this format, i.e. from "foo-bar" import * to import a module with - in it?

+80
python import module hyphen
Dec 02 2018-11-12T00:
source share
3 answers

You can not. foo-bar not an identifier. rename the file to foo_bar.py

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

 # contents of foo-bar.py baz = 'quux' 
 >>> execfile('foo-bar.py') >>> baz 'quux' >>> 
+59
Dec 02 '11 at 2:00
source share

If you cannot rename the module according to the 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 * 
+61
Dec 02 2018-11-12T00:
source share

If you cannot rename the source file, you can also use a symlink:

 ln -s foo-bar.py foo_bar.py 

Then you can simply:

 from foo_bar import * 
+31
Jan 09 '14 at 16:14
source share



All Articles