Using global variables between files?

前端 未结 7 1468
轻奢々
轻奢々 2020-11-22 03:43

I\'m bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.

What

7条回答
  •  渐次进展
    2020-11-22 04:13

    See Python's document on sharing global variables across modules:

    The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

    config.py:

    x = 0   # Default value of the 'x' configuration setting
    

    Import the config module in all modules of your application; the module then becomes available as a global name.

    main.py:

    import config
    print (config.x)
    

    or

    from config import x
    print (x)
    

    In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

提交回复
热议问题