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.)
Python packages and modules can not use hyphens, only underscores. This section of PEP-8 gives us guidance: Package and Module Names: Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.
¶ __main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs.
__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.
A module is a file containing Python code in run time for a user-specific code. A package also modifies the user interpreted code in such a way that it gets easily functioned in the run time.
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.
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