How to import module when module name has a '-' dash or hyphen in it?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Question
00:32 Accepted answer (Score 147)
01:21 Answer 2 (Score 219)
01:38 Answer 3 (Score 138)
02:05 Answer 4 (Score 54)
02:23 Thank you
--
Full question
https://stackoverflow.com/questions/8350...
Accepted answer links:
[Julien's answer]: https://stackoverflow.com/a/53516983/429...
Answer 2 links:
https://docs.python.org/3/library/import...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #import #module
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 Question
00:32 Accepted answer (Score 147)
01:21 Answer 2 (Score 219)
01:38 Answer 3 (Score 138)
02:05 Answer 4 (Score 54)
02:23 Thank you
--
Full question
https://stackoverflow.com/questions/8350...
Accepted answer links:
[Julien's answer]: https://stackoverflow.com/a/53516983/429...
Answer 2 links:
https://docs.python.org/3/library/import...
--
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")
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 *