如何从另一个模块获取函数中的模块变量? [英] How to get module variable in function from another module?

查看:320
本文介绍了如何从另一个模块获取函数中的模块变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个帮助函数,它能够在没有明确传递的情况下修改来自周围上下文的模块级变量(具有已知名称),例如

 #mod1.py 
mod_var = 1
modify_var()
#mod_var修改
打印mod_var

问题是 - 我不能通过 mod1.mod_var 引用变量,因为我想在许多模块中使用帮助函数(帮助器本身将在其他模块中定义);它应该从周围的呼叫上下文/范围动态地选择mod_var。



这可能吗?如何获取这个?



我的用例是增强在Django中定义URL - >视图映射。这些定义分布在许多定义 urlpatterns 模块级变量的子模块中。 Helper函数应该从调用它的模块中选取该变量并对其进行修改。



编辑:
有关其他解决方案 - 请检查这个答案。






Edit2:



/ strong>(留言在评论中引用)



最近我发现了另一种解决方案(在我看来最不神奇);
modify_var()函数可以这样实现:

  def modify_var():
call_module = __import __(__ main__)
call_module.mod_var = 42

潜在的利润是有争议的。



unittest 模块在其 main 方法。

解决方案

这是一个非常糟糕,可怕和可怕的想法,这将导致未来的维护噩梦。然而,Python确实提供了足够的绳子来射击自己的脚,如果你真的坚持:内省和元编程工具,这些工具主要用于调试目的,但可能被滥用来执行你非常渴望的不合理的任务。 / p>

例如,在 evil.py 中:

  import inspect 

def modify_var():
callersframe = inspect.stack()[1] [0]
callersglobals = callersframe.f_globals
如果'mod_var'不在callersglobals中:
raise ValueError,调用模块没有mod_var!'
callersglobals ['mod_var'] + = 1

现在说你有两个模块, a.py

  import evil 

mod_var = 23
evil.modify_var()
打印'一个mod_var :',mod_var

b.py

  import evil 

mod_var = 100
evil.modify_var()
打印b mod_var now:',mod_var

你可以做:

  $ python -c'import a;导入b'
a mod_var now:24
b mod_var now:101

然而,在未来保持这种黑魔法技巧 将变得头痛,所以我强烈建议这样做。


I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g.

# mod1.py
mod_var = 1
modify_var()
# mod_var modified
print mod_var

The problem is - I can't reference variable by mod1.mod_var, because I want to use helper function across many modules (helper itself will be defined in other module); it should dynamically 'pick' mod_var from surrounding calling context/scope.

Is this possible? How to obtain this?

My use case is to enhance defining URL -> view mapping in Django. Those definitions are spread across many sub-modules that define urlpatterns module-level variable. Helper function should pick this variable from the module that calls it and modify it. Avoiding explicitly passing it as argument would be great.

Edit: For additional solution - check this answer.


Edit2:

Wrong solution below! (left for references in comments)

Recently I've found another solution (the least magical in my opinion ;)) modify_var() function could be implemented like this:

def modify_var():
    calling_module = __import__("__main__")
    calling_module.mod_var = 42

Still, potential profits are arguable.

unittest module uses this technique in its main method.

解决方案

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.

这篇关于如何从另一个模块获取函数中的模块变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆