How can I get 'urlpatterns = __import__()' to work like a normal import statement?

I'm trying to create an import statement that's pluggable with other projects. This statement is located in urls.py

So this works:

from forum.urls import urlpatterns # Base Class: <type 'list'>

But this doesn't work:

from settings import ROOT_URLCONF as project_urls urlpatterns = __import__(project_urls) # Base Class: <type 'module'>

How can I get the latter to work?

-------------Problems Reply------------

urlpatterns = __import__(project_urls).whateversubmodule.urlpatterns

So you want to have import statements that are relative to earlier imports?

Definitely something I tried at one point. I had some very long import statements that had a common root, so I tried to factor it out. I could not get it to work with straight import statements, but maybe I didn't try hard enough.

Keep in mind that the import statement behavior by default is going to create a module object. It will then bind it into sys.modules, and then bind it in your current module's namespace with the name from the import statement. See http://docs.python.org/tutorial/modules.html.

A module object has a namespace. If a module is not a package, it's namespace comes from evaluating the contents of the .py file of the module. However, if it is a package then the namespace comes from the __init__.py module in the package. The other modules in the package are not imported automatically and are not available in the package's namespace. You have to import them separately.

The from...import statement will load the module into sys.modules. Then it will pull the object out of that module to which you referred in the import. Finally it binds that object into your current module's namespace with the name from the import statement. Basically you are copying a binding from one namespace to another. To be honest I find that it usually obfuscates the source of the name when you use it later (so I don't do it much).

To the point:

Your use of __import__ is one way around the limits of the import statement. See the python documentation. However, if you use a from..import statement don't try to reuse the resulting name in __import__ unless that is pointing to a module object (which it probably isn't). Imports need a dot-delimited sequence of module names only.

As well, keep in mind that just putting the explicit import may be a cleaner way to indicate where an object came from.

Category:python Views:1 Time:2010-08-27

Related post

  • Why are the Django project URLs not all available to the Django test client? 2010-08-20

    I've been trying to add the django-lean app to my project. The django-lean app is not located in the project I'm working on, it is on the PYTHONPATH. I have not been able to get the django-lean tests to pass. It seems the issue is that the TestCase d

  • How to force an ImportError on development machine? (pwd module) 2010-02-13

    I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils): try: import pwd do stuff except ImportError: do other stuff I want the import to fail, as it will on the actual GAE server, but the p

  • Python, dynamically invoke script 2010-03-06

    I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent. Normally you could do something like import mo

  • Detecting circular imports 2010-03-09

    I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project. Of course, when I add the circular import, I'm unaware of

  • Python : How to import a module if I have its path as a string? 2010-06-23

    Lets say I have path to a module in a string module_to_be_imported = 'a.b.module' How can I import it ? --------------Solutions------------- >>> m = __import__('xml.sax') >>> m.__name__ 'xml' >>> m = __import__('xml.sax', f

  • Django / Python, using variablized object names 2010-08-24

    I'm confused on how to do this, I'm passing in a dictionary with different values, such as "app" which is the name of the app (so that I can better decouple code for easier modularization).. so this is just a simplified example and its not working so

  • Why I can call 'print' from 'eval' 2010-10-16

    For code: #!/usr/bin/python src = """ print '!!!' import os """ obj = compile(src, '', 'exec') eval(obj, {'__builtins__': False}) I get output: !!! Traceback (most recent call last): File "./test.py", line 9, in <module> eval(obj, {'__builtins_

  • Multiple imports of the same file name 2010-12-22

    I am trying to create a plugin system and I have a function that imports all the modules into an array. Layout of Plugins: pluginsDir/ pluginsDir/chat pluginsDir/chat/main.py And this is the function that finds and imports the plugins: if os.path.exi

  • Check for existence of Python dev files from bash script 2011-01-31

    I am creating a simple bash script to download and install a python Nagios plugin. On some older servers the script may need to install the subprocess module and as a result I need to make sure the correct python-devel files are installed. What is an

  • Where to put static files that should be served directly under the server root? 2011-07-04

    I just migrated an old Django project to make use of the staticfiles app. Before that i had all needed files in a directory called static that got served directly under the server root. This directory is now served under STATIC_URL which is fine, exc

  • Plugin manager in python 2011-09-14

    I am relatively new to python (already did some 1h scripts like a little webserver or a local network chat) and want to program a plugin manager in it. My idea is, that there is an interface for plugins, that has the following features: getDependenci

  • managing django local and site settings with multiple developers? 2011-10-14

    After looking around I have come up with the following code this seems to work well I was wondering what others have come up with and feedback would be great. settings/init.py import sys import socket # try to import settings file based on machine na

  • Do PyImport_ImportModule and import statement load into different namespace? 2011-11-03

    Here is canonical example of a program extending embedded Python 3.x in C/C++: #include <Python.h> //// Definition of 'emb' Python module //////////////////// static PyObject* emb_foo(PyObject *self, PyObject *args) { char const* n = "I am foo"

  • How do you import a file in python with spaces in the name? 2012-02-03

    Do I have to take out all the spaces in the file name to import it, or is there some way of telling import that there are spaces? --------------Solutions------------- You should take the spaces out of the filename. Because the filename is used as the

  • django: grappelli: routing fails 2012-02-29

    I have installed grappelli via pip install (and subsequently updated it, to be sure). I put it before django.contrib.admin in INSTALLED_APPS: INSTALLED_APPS = ( ... 'grappelli', 'django.contrib.admin', My urls.py looks like this: url(r'^grappelli/',

  • how to do an embedded python module for remote sandbox execution? 2012-04-11

    I am trying to dynamically add python code to a sandbox module for executing on a remote machine. I am experiencing an issue with how to deal with imported methods. For example, it is common to see scripts written such as: from test_module import g i

  • Python how to alias module name (rename with preserving backward compatibility) 2014-06-20

    I have a python package named foo, which i use in imports: import foo.conf from foo.core import Something Now i need to rename the foo module into something else, let's say bar, so i want to do: import bar.conf from bar.core import Something but i wa

  • How can I import a python file through a command prompt? 2014-09-26

    I am working on project euler and wanted to time all of my code. What I have is directory of files in the form 'problemxxx.py' where xxx is the problem number. Each of these files has a main() function that returns the answer. So I have created a fil

  • How does one do the equivalent of "import * from module" with Python's __import__ function? 2008-09-29

    Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.107 (s). 11 q(s)