Note that there are some explanatory texts on larger screens.

plurals
  1. PORelative import creates different class object?
    text
    copied!<p>In a Django project, I have a directory structure that looks something like this:</p> <pre><code>project/ ├╴module_name/ │ ├╴dbrouters.py │ ... ... </code></pre> <p>In <code>dbrouters.py</code>, I define a class that starts out like this:</p> <pre><code>class CustomDBRouter(object): current_connection = 'default' ... </code></pre> <p>The idea is to have a database router that sets the connection to use at the start of each request and then uses that connection for all subsequent database queries similarly to what is described in the <a href="https://docs.djangoproject.com/en/1.5/topics/db/multi-db/#automatic-database-routing" rel="nofollow">Django docs for automatic database routing</a>.</p> <p>Everything works great, except that when I want to import <code>CustomDBRouter</code> in a script, <strong>I have to use the absolute path, or else something weird happens</strong>.</p> <p>Let's say in one part of the application, <code>CustomDBRouter.current_connection</code> is changed:</p> <pre><code>import project.module_name.dbrouters.CustomDBRouter ... CustomDBRouter.current_connection = 'alternate' </code></pre> <p>In another part of the application (assume that it is executed after the above code), I use a relative import instead:</p> <pre><code>import .dbrouters.CustomDBRouter ... print CustomDBRouter.current_connection # Outputs 'default', not 'alternate'! </code></pre> <p>I'm confused as to why this is happening. Is Python creating a new class object for <code>CustomDBRouter</code> because I'm using a different import path?</p> <p>Bonus points: Is there a better way to implement a 'global' class property?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload