惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
V
Visual Studio Blog
有赞技术团队
有赞技术团队
U
Unit 42
D
Docker
小众软件
小众软件
F
Full Disclosure
I
Intezer
Scott Helme
Scott Helme
P
Privacy International News Feed
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
B
Blog
Martin Fowler
Martin Fowler
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Spread Privacy
Spread Privacy
宝玉的分享
宝玉的分享
S
Security Affairs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
C
Cisco Blogs
云风的 BLOG
云风的 BLOG
Schneier on Security
Schneier on Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threat Research - Cisco Blogs
量子位
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Heimdal Security Blog
N
Netflix TechBlog - Medium
H
Hacker News: Front Page
P
Proofpoint News Feed
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
S
Schneier on Security

Jiajun的技术笔记

你好,2026! TiDB 源码阅读(六):TiDB Coprocessor 源码解析 性能优化的核心思想 TiDB 源码阅读(五):索引 TiDB 源码阅读(四):AST、逻辑计划、物理计划 CockroachDB Serverless Architecture podman 无故退出 Cursor Control-L (CTRL-L) Keyboard Shortcuts in Terminal Replace docker with podman Using xmonad with xfce4 A RC script for freebsd frpc 自己动手写一个k8s controller AI 会取代你的(编程)岗位吗? 自建DERP服务器提升Tailscale连接速度(使用Nginx转发) 自动升级Docker容器 再读《程序员修炼之道-从小工到专家》 让浏览器下载文件 再读《软件随想录》/《黑客与画家》/《软技能》 HTTP 压力测试中的 Coordinated Omission 2的补码 编程语言中的 context 是什么? flutter macOS 构建出错 Flatpak 使用小记 Golang CAS 操作是怎么实现的 PostgreSQL 当MQ来使用 Clash 结合 工作VPN 的网络设计 使用 PostgreSQL 搭建 JuiceFS PostgreSQL 配置优化和日志分析 有GitHub Copilot?那就可以搭建你的ChatGPT4服务 窗口函数的使用(以PG为例) 读《为什么学生不喜欢上学》 OpenAI Prompt Engineering 摘录和总结 读《打造真正的新产品》 VueJS 总结 Linux 自动挂载 alist 提供的webdav FreeBSD 使用 vm-bhyve 安装Debian虚拟机 FreeBSD 和 Linux 网卡聚合实现提速 GPT 帮我搞定了时区转换问题 长任务系统如何处理? macOS/Linux 编译 InputLeap 使用开源软KVM - synergy-core 解决 macOS 终端hostname一直变化问题 KVM 共享 Intel 集成显卡 PromQL 备忘 读《格鲁夫给经理人的第一课》 读《打开心智》 为什么要把复杂的联表操作拆成多个单表查询? 红包系统的设计 MySQL Index Condition Pushdown Optimization Go mod 简明教程 OpenWRT 使用 Android/iOS USB 网络 搭建旁路由 Golang gRPC 错误处理 编写可维护的单元测试代码 OAuth 2 详解(六):Authorization Code Flow with PKCE OAuth 2 详解(五):Device Authorization Flow OAuth 2 详解(三):Resource Owner Password Credentials Grant OAuth 2 详解(四):Client Credentials Flow OAuth 2 详解(二):Implict Grant Flow OAuth 2 详解(一):简介及 Authorization Code 模式 ElasticSearch 学习笔记 三种git流程以及发版模型 错误处理实践 权限模型(RBAC/ABAC) OIDC(OpenID Connect) 简介 任务队列简介 PostgreSQL 操作笔记 使用Drone CI构建CI/CD系统 Golang migrate 做数据库变更管理 使用PostgreSQL做搜索引擎 Nginx 源码阅读(三): 连接池、内存池 Nginx 源码阅读(二): 请求处理 Nginx 源码阅读(一): 启动流程 Go 泛型简明教程 KVM 显卡穿透给 Windows 使用 HTTP Router 处理 Telegram Bot 按钮回调 使用反射(reflect)对结构体赋值 GIN 是如何绑定参数的 你好 2022(2021 年终总结) 用Go导入大型CSV到PostgreSQL 使用 OpenWRT 搭建软路由 使用软KVM切换器 barrier 共享键鼠 SQL 防注入及原理 使用 gomock 测试 Go 代码 gevent不是黑魔法(二): gevent 实现 gevent不是黑魔法(一): greenlet 实现 用 entgo 替代 gorm 应用内使用crontab不是那么方便 单测时要不要 mock 数据库? Sentry 自建指南 用selenium完成自动化任务 用闲置的安卓手机做垃圾电话短信过滤 推荐三个时间管理工具 一次事故反思 当JS遇到uint64:JS整数溢出问题 SQLite3 存储以及ACID原理 Redis源码阅读:pub/sub实现 Redis源码阅读:zset实现 Redis源码阅读:bitmap 位图的运算 Redis源码阅读:set是怎么做交并集运算的?
再读 Python Language Reference
2017-01-24 · via Jiajun的技术笔记

https://docs.python.org/3.6/reference/ 重读笔记。

Lexical analysis

  • 在Python源文件中,空格将代码分割成token(s)。物理换行符(UNIX下的\n)对 Python程序没有实际意义,Python程序认定的是 NEWLINE

  • 在Python源文件中,一个Tab键在Python解释器解释的时候会被替换成8个空格的缩进, 而缩进对于Python有非常重要的意义。所以推荐在自己用的解释器里都把tab键替换成 4个空格(或者自己想要的空格数)。

    >>> def foo():
    ...     print("hello")  # 1 tab here
    ...     print("world")  # 4 spaces here
    File "<stdin>", line 3
    print("world")
                 ^
    IndentationError: unindent does not match any outer indentation level
    
  • NEWLINE

    • 显式join:使用\

      >>> if True\
      ... and False:
      ...     print("False")
      ...
      >>>
      
    • 隐式join:在小括号,中括号,大括号中的行都会被合并成逻辑行(只有一个NEWLINE)

      >>> (
      ... "hello"
      ... "world"
      ... )
      'helloworld'
      >>>
      

Data model

Python中每个对象都有自己的id,类型和值。

  • Python中的对象从对象的值的可变性上分为两类:

    • mutable,例如 dict, list
    • immutable,例如 str, tuple
  • 从理论上来讲,副作用例如打开一个文件,当此文件没有引用时是会被Python垃圾回收 的,但是由于gc无法做出保证(例如Python开启了DEBUG模式,所有的对象都会被一个 双链表链着,这个时候引用计数就不为0),所以最好还是自己显式关闭。

Execution model

  • Python程序由 code blocks 组成,block是Python执行代码的最小单元,block分为:

    • module
    • function body
    • class definition
    • 交互模式下每次输入的命令都是一个block
    • 每一个script file
    • $ python -c 'print("hello")' 中的命令也是一个block
    • 传递给 eval()exec() 的字符串也是一个block,但是这两个函数作用域规则有些特殊,会跳过LEGB中的E,也就是闭包。

每个block都在一个 execution frame 里执行。

  • name binding

    • 给函数传参数
    • import语句
    • 类和函数定义
    • 赋值语句
    • for语句的后面一个 for i in ...
    • with语句的as后面 with open(...) as ...
    • except后面的as
    • from ... import * 绑定所有非下划线开头的名字到当前命名空间
    • del 也是,虽然它的作用是删除绑定

只要出现了上述的binding,Python就认为这个变量名所指向的变量在当前的block里,所以:

In [1]: foo = "hello"

In [2]: def print_foo():
   ...:     print(foo)
   ...:     foo = "world"
   ...:

In [3]: print_foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-3-c80be14760b6> in <module>()
----> 1 print_foo()

<ipython-input-2-afc4cd9aff75> in print_foo()
      1 def print_foo():
----> 2     print(foo)
      3     foo = "world"
      4

UnboundLocalError: local variable 'foo' referenced before assignment

In [4]:
  • “The global statement has the same scope as a name binding operation in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.”

没看懂,来自:https://docs.python.org/3.6/reference/executionmodel.html

  • 类定义的变量作用域局限于类内,而不会扩展至方法和表达式,generator里,所以:

    In [1]: class Foo:
    ...:     hello = "hello"
    ...:     def foo(self):
    ...:         print(hello)
    ...:
    
    In [2]: Foo().foo()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-2-6c4f5adc4d1e> in <module>()
    ----> 1 Foo().foo()
    
    <ipython-input-1-029db0d572c9> in foo(self)
      2     hello = "hello"
      3     def foo(self):
    ----> 4         print(hello)
      5
    
    NameError: name 'hello' is not defined
    
    In [3]: class Foo:
    ...:     a = 32
    ...:     b = [a + i for i in range(10)]
    ...:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-3-395876c62295> in <module>()
    ----> 1 class Foo:
      2     a = 32
      3     b = [a + i for i in range(10)]
      4
    
    <ipython-input-3-395876c62295> in Foo()
      1 class Foo:
      2     a = 32
    ----> 3     b = [a + i for i in range(10)]
      4
    
    <ipython-input-3-395876c62295> in <listcomp>(.0)
      1 class Foo:
      2     a = 32
    ----> 3     b = [a + i for i in range(10)]
      4
    
    NameError: name 'a' is not defined
    
    In [4]:
    
  • 闭包内的变量(free variables)的值是在运行时确定的:

    In [1]: foo = "hello"
    
    In [2]: def f():
    ...:     print(foo)
    ...:
    
    In [3]: f()
    hello
    
    In [4]: foo = "world"
    
    In [5]: f()
    world
    
    In [6]:
    

The import system

  • import 语句包含两个部分

    • __import__ 搜寻指定名称的包
    • 然后将 __import__ 返回值在语句所在的scope里binding成那个名字
  • 导入的时候,会根据点号依次导入,而且会首先搜寻 sys.modules,例如:

    In [1]: import sys
    
    In [2]: sys.modules['tornado']
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-2-36f3d84239fe> in <module>()
    ----> 1 sys.modules['tornado']
    
    KeyError: 'tornado'
    
    In [3]: sys.modules['tornado.web']
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-3-f1a34b2734fb> in <module>()
    ----> 1 sys.modules['tornado.web']
    
    KeyError: 'tornado.web'
    
    In [4]: import tornado.web
    
    In [5]: tornado
    Out[5]: <module 'tornado' from '/usr/local/lib/python3.5/dist-packages/tornado/__init__.py'>
    
    In [6]: tornado.web
    Out[6]: <module 'tornado.web' from '/usr/local/lib/python3.5/dist-packages/tornado/web.py'>
    
    In [7]: sys.modules['tornado']
    Out[7]: <module 'tornado' from '/usr/local/lib/python3.5/dist-packages/tornado/__init__.py'>
    
    In [8]: sys.modules['tornado.web']
    Out[8]: <module 'tornado.web' from '/usr/local/lib/python3.5/dist-packages/tornado/web.py'>
    
    In [9]:
    

相关文章