Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module with a dash, or hyphen (-) in its name

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.)

like image 695
Skip Huffman Avatar asked Sep 28 '11 13:09

Skip Huffman


People also ask

Can Python module names have hyphens?

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.

What is __ main __ module in Python?

¶ __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.

What is __ import __ in Python?

__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.

What is a Python package vs module?

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.


1 Answers

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.

like image 155
nandhp Avatar answered Sep 23 '22 14:09

nandhp