Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference python package when filename contains a period

I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:

from "models.admin" import * 

however, I get a syntax error for having double quotes. But if I just do

from models.admin import * 

then I get "ImportError: No module named admin"

Is there any way to import from a python file that has a period in its name?

like image 379
Alexander Bird Avatar asked Dec 01 '09 18:12

Alexander Bird


People also ask

Can Python package name have a dash?

Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

What is the use of file __ init __ py in a package?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

What is __ init ___ py?

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

How do I include a file in a Python package?

Place the files that you want to include in the package directory (in our case, the data has to reside in the roman/ directory). Add the field include_package_data=True in setup.py. Add the field package_data={'': [... patterns for files you want to include, relative to package dir...]} in setup.py .


2 Answers

Actually, you can import a module with an invalid name. But you'll need to use imp for that, e.g. assuming file is named models.admin.py, you could do

import imp with open('models.admin.py', 'rb') as fp:     models_admin = imp.load_module(         'models_admin', fp, 'models.admin.py',         ('.py', 'rb', imp.PY_SOURCE)     ) 

But read the docs on imp.find_module and imp.load_module before you start using it.

like image 57
Cat Plus Plus Avatar answered Sep 28 '22 04:09

Cat Plus Plus


If you really want to, you can import a module with an unusual filename (e.g., a filename containing a '.' before the '.py') using the imp module:

>>> import imp >>> a_b = imp.load_source('a.b', 'a.b.py') >>> a_b.x "I was defined in a.b.py!" 

However, that's generally a bad idea. It's more likely that you're trying to use packages, in which case you should create a directory named "a", containing a file named "b.py"; and then "import a.b" will load a/b.py.

like image 38
Edward Loper Avatar answered Sep 28 '22 03:09

Edward Loper