dongwen1871 2015-03-06 17:44
浏览 83
已采纳

Python模块变量进入当前工作空间

As I've mentioned before I originally came from a Matlab background and then moved onto PHP before discovering Python. In both Matlab and PHP there were ways to create a scripts that when run all the variables got dumped into your current workspace. That workspace in Matlab being the interpreter when called from there or the function's workspace when called from a function. I would use this capability for constants - for example, plotting tools where you want to define a set of default fonts, line widths, etc.

Now in Python I can import a module but then all of the references constants in that module require either from {module} import * or {module}.{constant}.

This doesn't really limit me it is just an inconvenience. However, it would be nice to be able to import a constants file and just have the constants available to whatever called them.

I suspect Python does not allow this but I thought I would ask to see if someone had a clever work around.

  • 写回答

2条回答 默认 最新

  • dongshang6062 2015-03-06 18:04
    关注

    This isn't something you should normally be doing just to save a little typing, but here's one way you can do it:

    # define some constants
    PI = 3.1415927
    ANSWER = 42
    UNLUCKY = 13
    
    # put them into __main__ module (your interactive session)
    if __name__ != "__main__":
        import sys as _sys
        _sys.modules["__main__"].__dict__.update(
            dict((k, v) for (k, v) in globals().iteritems() if not k.startswith("_")))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料