importing as module when a file has a non-identifier name
I need to reuse a function in a file. The usual way is just to import this file as a module. But what to do if the name is "bad"? The following doesn't work:
import foo-bar as foo_bar
foo_bar.callme()
After trials and errors, the desired magic found:
foo_bar = __import__('foo-bar', globals(), locals(), [], -1)
foo_bar.callme()
See Python Documentation for details: in some cases you don't want to use __import__.
The best solution is, obviously, to rename file. But I wanted to find an answer to this importing challenge.
Categories:
python