[Python] Understand Scope in Python

Misunderstanding scope can cause problems in your application. Watch this lesson to learn how Python scope works and the hidden implications it presents. Local scope, nonlocal scope, and global scope variables are demonstrated and explained.

 

For example, we have the code:

复制代码
def whoami():
    def local_groot():
        i = "I am local groot"
        print(i) #"I am local groot"

    i = "I am groot"
    print(i) # "I am groot"

    # Call the local groot function
    local_groot()
    print(i) # "I am groot"
复制代码

Each function has its scope, won't conflict with outside function scope's variable.

 

For the case you do want to overwrite:

复制代码
def whoami():
    def local_groot():
        i = "I am local groot"
        print(i)

    def nonlocal_groot():
        nonlocal i
        i = "I am nonlocal groot"

    i = "I am groot"
    print(i) #"I am groot"
    nonlocal_groot()
    print(i) #"I am nonlocal groot"
复制代码

We can use 'nolocal' keyword.

 

There is also 'global' keyword, but you don't want to use it, it is not good pratice:

    def global_groot():
       global i
        i = "I am global groot"

 

posted @   Zhentiw  阅读(274)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-12-13 [CSS] Conditionally Apply Styles Using Feature Queries @supports
2016-12-13 [JS Compose] 2. Enforce a null check with composable code branching using Either
2014-12-13 [AngularJS] Using Services in Angular Directives
点击右上角即可分享
微信分享提示