The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping

--

Chapters
00:00 How To Import Module When Module Name Has A '-' Dash Or Hyphen In It?
00:24 Answer 1 Score 251
00:39 Accepted Answer Score 149
01:20 Answer 3 Score 140
01:41 Answer 4 Score 58
01:57 Answer 5 Score 13
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/8350...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #import #module

#avk47



ANSWER 1

Score 252


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 )




ACCEPTED ANSWER

Score 149


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


It's possible since Python 3.1+, see Julien's answer.


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.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 



ANSWER 3

Score 141


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

New module foo_proxy.py:

 tmp = __import__('foo-bar')
 globals().update(vars(tmp))

Module doing the import main.py:

 from foo_proxy import * 



ANSWER 4

Score 57


If you can't rename the original file, you could also use a symlink:

ln -s foo-bar.py foo_bar.py

Then you can just do:

from foo_bar import *