131

I have an existing python module with a dash in its name, foo-bar.py

Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work.

Is there a way to load a module whose name contains the typically forbidden '-'?

(I do understand that this isn't a best practice. But for this situation I would prefer not to redesign and test a much larger set of applications. Also I don't think my corporate masters would approve of my taking the time to implement such a change.)

codeforester
  • 39,467
  • 16
  • 112
  • 140
Skip Huffman
  • 5,239
  • 11
  • 41
  • 51
  • 3
    This answer in particular: http://stackoverflow.com/questions/761519/is-it-ok-to-use-dashes-in-python-files-when-trying-to-import-them/762693#762693 – BenH Sep 28 '11 at 13:06
  • 2
    Does this answer your question? [Is it ok to use dashes in Python files when trying to import them?](https://stackoverflow.com/questions/761519/is-it-ok-to-use-dashes-in-python-files-when-trying-to-import-them) – Georgy Aug 12 '20 at 14:36

2 Answers2

125

You can do that using __import__(). For example:

foobar = __import__("foo-bar")

But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.

nandhp
  • 4,680
  • 2
  • 30
  • 42
  • 4
    Thanks. I do understand that conventions should be followed wherever practical. I will be bringing up this specific issue during a departmental code review. – Skip Huffman Sep 28 '11 at 13:23
83

I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using __import__().

import importlib
mod = importlib.import_module("path.to.my-module")
# mod.yourmethod()

According to the docs:

"This provides an implementation of import which is portable to any 
Python interpreter. This also provides an implementation which is 
easier to comprehend than one implemented in a programming language 
other than Python."

Python 2.7 + only

NuclearPeon
  • 5,743
  • 4
  • 44
  • 52
  • 9
    I was searching for how to do this and your answer applies better to my situation than the older answer. It's always good if you see a distinct answer to the already existing one to add it as a new answer so that people in a position like myself can find all the relevant information in one place. – Davy M Aug 25 '17 at 23:47
  • 2
    in the python documentation, `__import__` is discouraged (see the [documentation](https://docs.python.org/3/library/functions.html#import__)) in the favor of `importlib`. it could cause a lot of issues. (see also [`this post`](https://stackoverflow.com/questions/1342128/problem-with-python-and-import)) – XxJames07- Mar 28 '22 at 10:36