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

PythonImportModuleHyphen

Python Problem Overview


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

foobar = __import__("foo-bar")

This does not:

from "foo-bar" import *

My question: Is there any way that I can use the above format i.e., from "foo-bar" import * to import a module that has a - in it?

Python Solutions


Solution 1 - Python

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 )

Solution 2 - Python

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.py
baz = 'quux'

>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

Solution 3 - Python

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 * 

Solution 4 - Python

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:

from foo_bar import *

Solution 5 - Python

Like other said you can't use the "-" in python naming, there are many workarounds, one such workaround which would be useful if you had to add multiple modules from a path is using sys.path

For example if your structure is like this:

foo-bar
├── barfoo.py
└── __init__.py

import sys
sys.path.append('foo-bar')

import barfoo

Solution 6 - Python

in Python 3.6 I had the same problem "invalid syntax" when directly

import 'jaro-winkler' as jw

said "No module named 'jaro-winkler'" when using:

jw = __import__('jaro-winkler')

and importlib.import_module() same.

finally i use pip uninstall the jaro-winkler module...just FYI

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBalaView Question on Stackoverflow
Solution 1 - PythonJulienView Answer on Stackoverflow
Solution 2 - PythonSingleNegationEliminationView Answer on Stackoverflow
Solution 3 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 4 - PythongitaarikView Answer on Stackoverflow
Solution 5 - PythonReda DrissiView Answer on Stackoverflow
Solution 6 - Pythonkk120120View Answer on Stackoverflow