Python builtins — Built-in objects and __main__ — Top-level script environment

 builtins — Built-in objects
This module provides direct access to all ‘built-in’ identifiers of Python; for example, builtins .open is the full name for the built-in function open(). See Built-in Functions and Built-in Constants for documentation.
This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly:
import builtins
def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...


As an implementation detail, most modules have the name__builtins__ made available as part of their globals. The value of__builtins__ is normally either this module or the value of this module’s__dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.



 __main__ — Top-level script environment


'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to'__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own__name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with-m.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值