Dashes are not illegal but you should not use them for 3 reasons: You need special syntax to import files with dashes. Nobody expects a module name with a dash. It's against the recommendations of the Python Style Guide.
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
In Python, Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.
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 )
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'
>>>
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 *
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 *
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With