Use of “global” keyword in Python

后端 未结 10 2450
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  太阳男子
    2020-11-21 05:32

    This is explained well in the Python FAQ

    What are the rules for local and global variables in Python?

    In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

    Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

    https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

提交回复
热议问题