tags:

views:

61

answers:

1

I've got some code that runs on every (nearly) every admin request but doesn't have access to the 'request' object.

I need to find the path to Django installation. I could do:

import django
django_path = django.__file__

but that seems rather wasteful in the middle of a request.

Does putting the import at the start of the module waste memory? I'm fairly sure I'm missing an obvious trick here.

+2  A: 

So long as Django has already been imported in the Python process (which it has, if your code is, for example, in a view function), importing it again won't do "anything"* — so go nuts, use import django; django.__file__.

Now, if Django hasn't been imported by the current Python process (eg, you're calling os.system("myscript.py") and myscript.py needs to determine Django's path), then import django will be a bit wasteful. But spawning a new process on each request is also fairly wasteful… So if efficiency is important, it might be better import myscript anyway.

*: actually it will set a value in a dictionary… But that's "nothing".

David Wolever
This is in a template tag. I originally assumed 'django' would be visible but I got a NameError. Maybe something else is causing that?
andybak
You do need to explicitly import `django` for the name to be visible. However, Python does cache imports, so it won't be re-imported. You can see how this works by looking at `sys.modules`. Basically, when you say `import foo`, if `sys.modules['foo']` exists, that will be used.
David Wolever
It's the caching of imports that I wasn't clear on. I assume though it only works if you import in exactly the same way? i.e. I would suffer a penalty for imports such as 'import django as' or 'from django import ...'
andybak
Nope - it's pretty smart about canonicalizing (sp?) imports. Eg: `>>> import django as foo; sys.modules['django'] --> <module ...>`, `>>> from django import db; sys.modules['django'] --> <module ...>`.
David Wolever