__name__ 特殊变量用于检查文件是否已作为模块导入,并通过其 __name__ 属性识别函数、类和模块对象。

Section 78.1: __name__ == '__main__'

特殊变量 __name__ 不是由用户设置的。它主要用于检查模块是自己运行的,还是因为执行了 import 而运行的。为了避免模块在被导入时运行其代码的某些部分,请检查 if __name__ == '__main__'。

module_1.py 脚本文件只有一行:

import module2.py

让我们看看在 module2.py 中发生了什么情况

Situation 1

module2.py

print('hello')

运行 module1.py 将打印 hello

运行 module2.py 将打印 hello

Situation 2

module2.py

if __name__ == '__main__':
  print('hello')

运行 module1.py 将不会打印任何内容

运行 module2.py 将打印 hello

Section 78.2: 在日志记录中使用

在配置内置的 “日志 ”功能时,一种常见的模式是使用当前模块的“name”创建一个日志记录器:

logger = logging.getLogger(__name__)

这意味着模块的全称将出现在日志中,从而更容易查看消息的来源。

Section 78.3: 函数类或 module.__name__

函数、类或模块的特殊属性 __name__ 是一个包含其名称的字符串。

import os

class C:
  pass

def f(x):
  x += 2
  return x

print(f)
# <function f at 0x029976B0>
print(f.__name__)
# f

print(C)
# <class '__main__.C'>
print(C.__name__)
# C

print(os)
# <module 'os' from '/spam/eggs/'>
print(os.__name__)
# os

函数类或 module.__name__

然而,__name__ 属性并不是引用类、方法或函数的变量的名称,而是在定义时赋予它的名称。

def f():
  pass

print(f.__name__)
# f - as expected

g = f
print(g.__name__)
# f - even though the variable is named g, the function is still named f

函数类或 module.__name__

除其他外,还可用于调试:

def enter_exit_info(func):
  def wrapper(*arg, **kw):
    print('-- entering', func.__name__)
    res = func(*arg, **kw)
    print('-- exiting', func.__name__)
    return res
  return wrapper

@enter_exit_info
def f(x):
  print('In:', x)
  res = x + 2
  print('Out:', res)
  return res

a = f(2)

# Outputs:
# -- entering f
# In: 2
# Out: 4
# -- exiting f

函数类或 module.__name__