28
3

I was somehow surprised by the following behavior:

  1. def main():
  2. print "%s" % foo
  3. if __name__ == "__main__":
  4. foo = "bar"
  5. main()

i.e. a module function has access to enclosing variables in the __main__. What's the explanation for it?

SilentGhost

206k4949 gold badges271271 silver badges268268 bronze badges
asked Jan 23 '11 at 18:30
David Cournapeau

59.5k77 gold badges5757 silver badges6767 bronze badges
  • 4
    There's no scope __main__. There's an if that happens to compare a variable that happens to be called __name__ to something that happens to be the string literal "__main__". – user395760 Jan 23 '11 at 18:53
  •  
    @delnan: __main__ is a module, and each module has an associated scope. Try import __main__; type(__main__) in the interpreter (not in IPython). – Sven Marnach Jan 23 '11 at 21:48
  •  
    @Sven: I know. OP should know at some point. But it seemed to me OP instead confuses if statements with parts of the condition and think if introduces a new scope - which would be a more pressing issue. (Admittedly, "There is no scope __main__ is misleading, strictly speaking) – user395760 Jan 23 '11 at 21:50
  • 1
    @delnan: you're right. In retrospect, I don't know why I was confused. Maybe debugging code at 3 a.m is not such a good idea after all :) – David Cournapeau Jan 24 '11 at 1:30
  •  
    I just stumbled over this exact same behaviour...thought I was going mad. Glad to see someone else has already asked this question! The behaviour is obvious when the answer is explained... – ccbunney Jun 28 '13 at 8:58

4 Answers

25
 

Variables in the current modules global scope are visible everywhere in the module -- this rule also holds for the __main__ module.

From Guido's tutorial:

At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

  • the innermost scope, which is searched first, contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
  • the next-to-last scope contains the current module’s global names
  • the outermost scope (searched last) is the namespace containing built-in names
answered Jan 23 '11 at 18:32
Sven Marnach

375k8484 gold badges766766 silver badges710710 bronze badges
7

The thing here is that:

  1. if __name__ == "__main__":
  2. foo = "bar"

defines a global variable named foo in that script. so any function of that module will have access to it.

The piece of code listed above is global to the module and not inside any function.

answered Jan 23 '11 at 18:34
Santiago Alessandri

5,0682424 silver badges4242 bronze badges
6

foo is a module global variable (it's not in any function). All scopes within the module can access it.

answered Jan 23 '11 at 18:32
sinelaw

12.9k11 gold badge3636 silver badges7373 bronze badges
2

In python there's the global scope, and functions have their own scopes. So it you define foo under the name==main, it's in the global scope. Also, it's not a mistake to use a variable which hasn't been declared yet, in a function, if it will be declared by the time the function will be called.

answered Jan 23 '11 at 18:34
kynnysmatto

2,4931717 silver badges23

python __main__ 里的变量是全局变量 因此在函数里面可以访问到的更多相关文章

  1. python世界里的局部变量和全局变量: 潜规则太重要了!!!

    python世界里的局部变量和全局变量: 潜规则太重要了!!! 先上代码: def fun(): def test_global(): ''' 内层和外层都需要声明为global, 才能彻底打通变量名 ...

  2. python学习-day15:局部变量与全局变量、嵌套函数、递归

    一.全局变量与局部变量 在子程序中定义的变量称为局部变量, 在程序的一开始定义的变量称为全局变量. 全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序.当全局变量与局部变量同名时:在定义局部 ...

  3. python正则表达式里引入变量

    import re def reg_exp(senten): jiqiren = "阿童木" matchObj1 = re.search( r'(你(.*?)(男|女))|(机器( ...

  4. python做中学(一)全局变量的用法

    一段时间没有使用python来写代码,就发现以前学习的很多语法都忘了.看来还是当初这方面的项目做的好不够多,没有系统性的运用和学习,导致了很多语法不能顺手拈来.在接下来的这个项目中, 一定要把遇到的一 ...

  5. 如何查看 Python 全部内置变量和内置函数?

    https://jingyan.baidu.com/article/7082dc1c071649e40a89bdb8.html Python 解释器内置了一些常量和函数,叫做内置常量(Built-in ...

  6. Python第七天 函数 函数参数 函数里的变量 函数返回值 多类型传值 函数递归调用 匿名函数 内置函数

    Python第七天   函数  函数参数   函数里的变量   函数返回值  多类型传值     函数递归调用   匿名函数   内置函数 目录 Pycharm使用技巧(转载) Python第一天   ...

  7. 说几个python与c区别的地方以及静态变量,全局变量的区别

    一: python代码: a = 2 def b(): print a a = 4 print a b() 在b函数中,有a=4这样的代码,说明a是函数b内部的局部变量,而不是外部的那个值为2的全局变 ...

  8. python 本地变量和全局变量 locals() globals() global nonlocal 闭包 以及和 scala 闭包的区别

    最近看 scala ,看到了它的作用域,特此回顾一下python的变量作用域问题. A = 10 B = 100 print A #10 print globals() #{'A': 10, 'B': ...

  9. python开发_python中的变量:全局变量和局部变量

    如果你在为python中的变量:全局变量和局部变量头疼,我想这篇blog会给你帮助 运行效果: 代码部分: #Python中的变量:全局变量和局部变量 #在很多语言中,在声明全局变量的时候,都喜欢把全 ...

随机推荐

  1. node版本切换工具n的使用介绍

    全局安装 npm install -g n mac的安装目录/usr/local/n/versions/node/13.2.0 因此首先在/usr/local/创建目录n,修改权限为普通访问权限,这样 ...

  2. python递归函数(10)

    一个函数在函数体内部调用自己,这样的函数称为递归函数,递归的次数在python是有限制的,默认递归次数是997次,超过997次会报错:RecursionError. 一.递归函数案例 案例一:计算数字 ...

  3. log4j测试示例

    引入依赖 <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId> ...

  4. 07 XML知识点--学习笔记

    1.XML概念:Extensible Markup Language 可扩展标记语言 可扩展:标签都是自定义的. <user> <student> 功能 * 存储数据 1. 配 ...

  5. [转帖]【MySQL+keepalived】用keepalived实现MySQL主主模式的高可用

    [MySQL+keepalived]用keepalived实现MySQL主主模式的高可用 https://www.jianshu.com/p/8694d07595bc 一.实验说明 MySQL主主模式 ...

  6. [HAOI2015]树上操作 题解

    题目描述 有一棵点数为 N 的树,以点 1 为根,且树点有边权.然后有 M 个操作,分为三种: 操作 1 :把某个节点 x 的点权增加 a . 操作 2 :把某个节点 x 为根的子树中所有点的点权都增 ...

  7. 使用Python快速实现简单的人脸检测

    最近有个比较要好的朋友问我能不能从监控视频里识别到从监控跟前经过的指定的人.因为他们单位的监控室经常要花大量的人力跟时间去找某个人在哪个位置出现过的证据.听起来像是一份比较有挑战性的任务,就答应他试试 ...

  8. pymysql 模块简单使用

    目录 pymysql 模块简单使用 安装 pymysql 模块 使用 pymysql 连接数据库 并插入数据 使用pymysql 插入数据 修改查询显示结果 pymysql 模块简单使用 安装 pym ...

  9. python基础 — Queue 队列

    queue介绍 queue是python中的标准库,俗称队列. 在python中,多个线程之间的数据是共享的,多个线程进行数据交换的时候,不能够保证数据的安全性和一致性,所以当多个线程需要进行数据交换 ...

  10. 01-打印Hello World、变量

    一.打印Hello World 下面就是我们写的打印hello world程序 在go语言中://代表单行注释,/**/代表多行注释 //单行注释 /* 多行注释 多行注释 */ package ma ...