4👍
It’s a truly bad, horrible, and awful idea, which will lead to future maintenance nightmares. However, Python does offer “enough rope to shoot yourself in the foot”, if you truly insist: introspection and metaprogramming tools which are mostly intended for debugging purposes, but can be abused to perform the ill-conceived task you so desperately crave.
For example, in evil.py
:
import inspect
def modify_var():
callersframe = inspect.stack()[1][0]
callersglobals = callersframe.f_globals
if 'mod_var' not in callersglobals:
raise ValueError, 'calling module has no "mod_var"!'
callersglobals['mod_var'] += 1
now say you have two modules, a.py
:
import evil
mod_var = 23
evil.modify_var()
print 'a mod_var now:', mod_var
and b.py
:
import evil
mod_var = 100
evil.modify_var()
print 'b mod_var now:', mod_var
you could do:
$ python -c'import a; import b'
a mod_var now: 24
b mod_var now: 101
However, maintaining this kind of black-magic tricks in the future is going to be a headache, so I’d strongly recommend not doing things this way.
4👍
What you want to do sounds like too much magic. Pass in urlpatterns and be done with it. Explicit is better than implicit.
- [Django]-Pass a lazy translation string including variable to function in Django
- [Django]-Django ORM: Joining QuerySets
- [Django]-Django queryset "contains" for lists, not strings
- [Django]-Django AMQP error
2👍
OK, here’s the magic, but again, I recommend not using it:
import sys
def modify_var():
"""Mysteriously change `mod_var` in the caller's context."""
f = sys._getframe(1)
f.f_locals['mod_var'] += " (modified)"
mod_var = "Hello"
modify_var()
print mod_var
prints:
Hello (modified)
As a further warning against this technique: _getframe
is one of those functions that other implementations of Python don’t provide, and the docs include this sentence: “This function should be used for internal and specialized purposes only.”
- [Django]-How to tell Django, that memcached running with item-size larger than default?
- [Django]-Check if a non-nullable field is null
0👍
If you really want to do that then you’ll need to import mod1 in either the other module or directly in the function, and then modify it off that import. But don’t do that; seasoned programmers will point and laugh.
- [Django]-Django: Give date field default value of one month from today
- [Django]-Django global filter
- [Django]-Get list_display in django admin to display the 'many' end of a many-to-one relationship