search
HomeBackend DevelopmentPython TutorialDefault scope and closures in Python and Lua

Default scope

I learned Lua some time ago and found that the default scope of Lua is opposite to that of Python. When Lua defines a variable, the default scope of the variable is global. This is not very accurate. When Lua executes a statement such as x = 1, it will search for x layer by layer starting from the current environment. Only when it cannot find x Global variables are defined only under certain circumstances), and when Python defines a variable, the scope of the variable is local (current block) by default. In addition, Lua can define local variables by adding the local keyword before the variable when defining the variable, but Python does not have a similar keyword, and Python variables can only be defined in the current block.

We know that global variables are bad, but local variables are good. When writing programs, you should try to use local variables. So at the beginning, I thought Python's convention was better. Its advantage is that it requires less typing. When writing Lua programs, I keep saying "Don't forget local, don't forget local" in my heart. However, sometimes a few things slip through the net and cause some magical bugs.

Closures

The first time I realized the problem of Python's default scope was when using closures. Regarding closures, there is a piece of code in the Lua tutorial:

function new_counter()
  local n = 0
  local function counter()
    n = n + 1
    return n
  end
  return counter
end
   
c1 = new_counter()
c2 = new_counter()
print(c1())  -- 打印1
print(c2())  -- 打印1
print(c1())  -- 打印2
print(c2())  -- 打印2

The essence of closures can be referred to the environment model in Chapter 3 of SICP. Here you can simply imagine that the function counter has a private member n.

Now the question comes: I want to use Python to implement a closure with the same function?

First, directly rewrite the Lua code into Python code:

def new_counter():
  n = 0
  def counter():
    n = n + 1
    return n
  return counter

Then I was dumbfounded: This program cannot run, and the unassigned variable n is accessed in line 4. The reason for the error is not that Python does not support closures, but that Python’s assignment operation cannot access the upper-level variable n (in fact, Python considers it to be a definition of local variables, not an assignment. Defining local variables and assignment operations in Python Syntactically conflicting, Python simply supports only redefinable definition statements). Since Python's default scope is local, when the program runs to n = n + 1, Python thinks this is a variable definition operation, so it creates an (uninitialized) local variable n - and successfully overwrites new_counter n at this level - then try to assign n + 1 to n, but n is not initialized, n + 1 cannot be calculated, so the program reports an error.


You can use a little trick to implement the function of closure assignment:

def new_counter():
  n = [0]
  def counter():
    n[0] = n[0] + 1
    return n[0]
  return counter

The reason why n[0] = n[0] + 1 will not go wrong is that the equal sign here and the preceding n The equal sign of = n + 1 has different meaning. The equal sign in n[0] = n[0] + 1 means to modify an attribute of n. In fact, this equal sign ultimately calls the __setitem__ method of list. The equal sign in n = n + 1 means to bind the value n + 1 to symbol n in the current environment (if symbol n already exists in the current environment, overwrite it).

Another digression: Damn it, I don’t need to write it this way, it’s so ugly. Anyway, Python is an object-oriented language. To implement a counter, you might as well write a class.

Separation of definition and assignment

First, let’s summarize the characteristics of the default scope of Python and Lua:

1. Lua’s default scope is global. When writing a program, remember the local keyword (unless you really want to define a global variable) , if you accidentally forget local, there will be no prompt, just wait for the bug to be corrected.

2. Python’s default scope is local. Although the mental burden of writing a program is less, it loses the ability to assign values ​​to upper-level variables (it can be changed, but it will make the language more confusing).

It seems that both default scopes have problems? Personally, I think the reason for the above problems is that Python and Lua do not realize the separation of definition and assignment. In Python and Lua, a statement like x = 1 can represent either a definition or an assignment. In fact, not only these two languages, but many high-level languages ​​do not realize the separation of definition and assignment. Definition and assignment are similar in function, but they are essentially different.

The following uses x = 1 as an example to explain the definition and assignment:

The definition means: register the symbol x in the current environment and initialize it to 1. If x already exists, an error is reported (redefinition is not allowed) or overwritten (redefinition is allowed).

Assignment means: starting from the current environment, looking up layer by layer until the symbol x is found for the first time, and changing its value to 1. If it cannot be found, an error will be reported (the variable does not exist).

Now we slightly modify Python to achieve the separation of definition and assignment: use ":=" to indicate definition and "=" to indicate assignment. Then rewrite the new_counter example that cannot run (the assignment operation in Python conflicts with the definition of local variables. In other words, Python actually does not have an assignment operation, so we only need to simply replace all "=" with ":="") , see where it goes wrong:

def new_counter():
  n := 0
  def counter():
    n := n + 1
    return n
  return counter

It’s obvious why this program is wrong. What we want in line 4 is an assignment operation, not a definition operation. Modify it to the correct writing:

def new_counter():
  n := 0
  def counter():
    n = n + 1
    return n
  return counter

This way it can run correctly (provided there is a modified version of the Python interpreter XD).

Finally, let’s talk about Lua. Lua feels like half of the separation of definition and assignment has been achieved. The equal sign statement with the local keyword must be defined. The problem is the equal sign statement without local. For this kind of statement, Lua does this: first try to do the assignment, and if the assignment fails (the variable does not exist), define the variable in the outermost environment (global environment). In other words, the equal sign statement without local mixes definition and assignment. In addition, if the separation of definition and assignment is achieved, there is no need to consider the issue of default scope - all definitions are defined in the current environment, and they all define local variables. I really can't think of any benefit to defining global variables in a function body or some other block.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.