Data Model

type and object

python中大部分变量所指示的实体都是某个类型的实例对象(obj),并且有的obj本身还是类型,比如class和metaclass

  • metaclass的实例对象为 class
  • class的 实例对象为 普通对象
  • 继承相当于类型间的平级关系,而类型与实例对象之间的关系是层次关系
    • 使用obj.class/type(obj) 查看某个实例对象的类型
    • 使用class.mro/class.mro()/inspect.getmro() 查看某个类型的继承关系
  • 为了避免递归
    • type的类型是type,所有metaclass的类型都是type,object的类型是type,
    • 所有类型的默认父类和最顶层基类都是object
    • 所有非元类类型的默认元类都是type
  • new函数用于生成实例对象并返回
  • init函数用于对new生成的实例对象进行初始化,不需返回值
  • call函数用于处理实例对象 obj() 等情形,对于元类而言,一般会转交给type.call进行处理,生成类实例对象。 ```python class MetaClass(type):

    类为MetaClass,该类的实例是一个类对象

    def new(cls, classname, bases, classdict, args, *kwargs):

    1. # 这里的cls和普通的类一样,自然表示当前的类MetaClass
    2. # 覆盖type.__new__, 参数固定
    3. # 使用type.__new___生成一个类对象
    4. return type.__new__(cls, classname, bases, dict(classdict)) # 见后面
    5. # return super().__new__(cls, classname, bases, classdict)

    def init(self, classname, bases, classdict, args, *kwargs):

    1. # 使用__new__生成的类对象,可以在这里进行初始化。
    2. type.__init__(self, classname, bases, classdict)
    3. # super().__init__(classname, bases, classdict)
    4. # 本身的操作

    def call(self, args, *kwargs):

    1. # 类对象的()方法,用于生成实例对象
    2. return type.__call__(self)
    3. # return super().__call__(*args, **kwargs)

    @classmethod def prepare(cls, clsname, bases, args, *kwargs):

    1. return OrderedDict({"a": 1, "show": lambda : print(1) })

class A(object, metaclass=MetaClass): def new(cls, args, *kwargs):

  1. # 这里cls表示A
  2. # 调用object.__new__生成该类的一个实例对象
  3. return object.__new__(cls)
  4. # super().__new__(cls)
  5. # 其他的类方法就很普通了
  6. def __init__(self, *args, **kwargs):
  7. super().__init__(*args, **kwargs)
  8. # 本身的操作
  9. # 这个方法控制的是a()的行为,而不是A()的行为
  10. # A() 的行为由生成A的元类MetaClass所控制
  11. def __call__(self, *args, **kwargs):
  12. pass
  13. def show(self):
  14. pass

type 伪代码

class type(): def call(cls, args, *kwarg):

  1. # ... maybe a few things done to cls here
  2. instance = cls.__new__(cls, *args, **kwargs)
  3. # instance = cls(*args, **kwargs)
  4. if isinstance(instance, cls):
  5. # ... maybe a few things done to the instance here
  6. # then we initialize the instance with its __init__() method
  7. instance.__init__(*args, **kwargs)
  8. # ... maybe a few more things done to instance here
  9. return instance
  10. # 注意上面代码中的 if 语句,如果生成的对象不是 cls 的实例,则不会调用 Init,而是直接返回
  1. - ** obj()** 等价于 **type(obj, *args, **kwargs).__call__(obj, *args, **kwargs)**
  2. - 大部分类型的的**实例对象**都是通过 **obj()** 产生
  3. - 其本质为type(obj).__call__内部调用了__new__生成实例对象,之后再调用了__init__对实例对象进行了初始化
  4. - 由于**metaclass的类型和基类**都是**type**,由上面的代码可知 **type.__call__**实现为
  5. - instance = self.**__new__**(self, *args, **kwargs)
  6. - if isinstance(instance, self): self.**__init__**(instance, *args, **kwargs)
  7. - return instance
  8. - 只能通过type.__new__(metaclass, classname, bases, dict)生成 class
  9. - 只能通过object.__new__(cls) 生成 普通对象
  10. - 可以看到,无论是class还是普通对象的生成,都是type.__call__驱动的,而真正的对象则分别由type.__new__(metcalss, classname, bases, dict)和object.__new__(cls) 生成的
  11. - metaclass的__prepare__类方法需要返回一个mapping对象
  12. - 其会被作为class clsname:形式定义类时的初始命名空间,其可以为非空,用于给类的命名空间设定初始值
  13. - 调用该函数时会传入__new__中除了classdict之外的所有参数
  14. ```python
  15. # 1. x = obj()
  16. x = obj(*args, **kwargs) # 等价于
  17. x = cls.__call__(obj, *args, **kwargs)
  18. # 2. obj = cls()
  19. obj = cls(*arg, **kwargs) # 等价于
  20. obj = metaclass.__call__(cls, *args, **kwargs)
  21. # 3. cls = metaclass()
  22. cls = metaclass("clsname", bases, attrs, *args, **kwargs) # 等价于
  23. cls = type.__call__(metaclass, "clsname", bases, attrs, *args, **kwargs)
  24. # class cls(metaclass=metaclass):
  25. class cls(*bases, metaclass=metaclass, *args, **kwargs):
  26. attrs # 等价于
  27. if (hasattr(metaclass, "__prepare__")):
  28. base_attrs = metaclass.__prepare__(
  29. metaclass, "clsname", bases, *args, **kwargs)
  30. base_attrs.update(attrs)
  31. else
  32. base_attrs = attrs;
  33. cls = metaclass("clsname", bases, base_attrs, *args, **kwargs)
  34. # 由class cls的原理所知,下面的写法也是支持的
  35. def meta(clsname, bases, attrs):
  36. return type.__new__(type, clsname, bases, attrs)
  37. # return type(clsname, bases, attrs)
  38. meta.__prepare__ = lamda *args, **kwargs : OrderedDict({2: 1})
  39. class A(metaclass=meta):
  40. pass
  41. # 当然,也可以不调用__call__,那么自己进行实例对象生成以及初始化
  42. B = MetaClass.__new__(MetaClass, 'B', (object,), {'show': show})
  43. B.__init__('B', (object,), {'show': show})
  44. C = type.__new__(type, 'C', (object,), {'print': display})
  45. C.__init__('C', (object,), {'print': display})

Creating class functionally

  1. # 1. 直接调用type.__class__生成
  2. type.__call__(metaclass, clsname, bases, attrs, *args, **kwargs)
  3. type(clsname, baes, attrs, *args, **kwargs)
  4. # 2. 使用types.new_class
  5. C = types.new_class('ClassName', (object, ),
  6. {'metaclass': MetaClass, arg1: 123},
  7. lambda namespace: ns.update(attrs))
  8. # namespace要么是Metaclass.__prepare__返回的mapping,要么是空mapping
  9. # 之后该函数会把lamda函数返回的mapping转递给meta_class.__new__中

Attribute

python中的作用域通常用一个类似字典的对象dict来表示,其内的名字一般称作 attributes

  • class.dict是一个mappingproxy 对象,是只可读的,但是可以用cls.attr = value或者setattr(cls, attr, value)更改,里面存了所有对象所共享的方法和数据
  • obj.dict是一个dict对象,自然可读可写,里面存了每个对象所特有的数据
  • 类定义中的变量会被添加到一个字典中,收集起来后通过
  • 一个py文件,即module,也属于一个作用域,使用sys.modules[name]进行访问

Builtin functions and magic method

  • vars(obj) 返回对象的dict属性
    • 当参数为空时,返回local作用域,即vars() == locals()/vars(sys.modules[name])
  • dir(obj) 返回该对象可访问的属性列表
    • 如果该对象类型定义了dir()方法,则返回调用该函数返回结果的排序版本
    • 否则,从该对象开始,到其基类,将所有继承体系内的属性收集起来并返回
    • 主要用于IDE交互显式
  • .attr/getattr(obj, attr)
    • 总是调用(即使是obj.dict,或者其他魔法方法)继承而来的getattribute,最终必须要调用其基类的getattribute,对于普通的类而言为object.getattribute
      • 其内部为首先查找名字是否在于obj的dict内,
      • 否则到所有继承层级中寻找
      • 对于找到的的带get的descriptor,则会调用get函数
    • 如果没找到,或者中途抛出AttributeError,在getattr存在的情况下调用getattr
    • 否则抛出AttributeError
    • 由于其强制性,如果没有正确调用object.getattribute的话,会造成无限递归
  • .attr = value/ setattr(attr, value)
    • 与getattr()相反,该操作优先调用type(obj).setattr(),当不存在时才作用其内的dict
    • 注意obj.dict[‘name’] = 3不属于这一类, 因为这里是调用了getattribute_(self, “dict“)
  • hasattr(obj, attr)
    • 调用getattr(obj, attr),如没有AttributeError异常,返回True
  • del obj.attr/ delattr(obj, attr)
    • 优先调用delattr,当不存在时作用于其内的dict
  • Special method lookup
    • 指的是当使用builtin函数或者某些语法隐式调用魔法方法的时候,只会查看其继承链中的类型是否有该魔法方法(不会调用getattribute),即使obj内dict中有同名方法也没用,没找到还是抛出AttributeError
    • 基本上除了上述的情况外,都满足该规则,但是要注意的是,显式调用还是会正常的调用链,如obj.len() ```python

      由于getattribute 不正确定义引起的无限递归情况

      def getattribute(self, attr): # 无限递归 return self.dict[attr] # 这里又发生getattribute调用 return super().getattribute(self, attr) # 正确使用方法,最终会调用object.getattribute

Special method lookup

class Meta(type): … def getattribute(args): … print(“Metaclass getattribute invoked”) … return type.getattribute(args) … class C(object, metaclass=Meta): … def len(self): … return 10 … def getattribute(args): … print(“Class getattribute invoked”) … return object.getattribute(args) … c = C() c.len() # Explicit lookup via instance Class getattribute invoked 10 type(c).len(c) # Explicit lookup via type Metaclass getattribute invoked 10 len(c) # Implicit lookup 10 ```

  • slots
    • 在类定义中使用,值为字符串,iterable,用于指示该类需要的属性变量。使用slots后会禁止生成dict, wickref等等属性,可以节约空间
  • str
    • 使用print() 和 format()时会调用该方法,用于显示Informal information,如未实现则调用repre
  • repr
    • repre()或者在控制台显示,会调用该方法,用于显示formal information,最好返回一个可以eval生成该对象的字符串。object自带repr,即显示对象的地址,名称信息
  • bytes
    • bytes()会调用,需要返回字节串
  • lt(self, other)/eq(self, other)
    • 用于比较的重载操作符,使用类装饰器functools.total_ordering可以只需实现lt和eq就行,其他的比较符会自动生成
  • format(self, formatspec)
    • str.format()或者 % 或者 fstring 会调用该方法,formspec为传入的各种修饰信息
  • hash
    • 用于set和dict中计算hash值使用
  • bool
    • 需要你转换为bool值时,如果该方法未实现则会尝试len,如果还没有,则所有objec返回True

即调用一个方法,function本身是一个实现了get的function对象,其存在于type(obj).dict中
首先通过属性访问找到该function object, 一般位于__class__.__dict__中

  • 寻找到后将自己作为self参数传入该function object.__get__中,转换成一个bound method, 并返回, 其内有:

    • __func__ 原始的function object
    • __self__ 绑定的对象
    • 所以说每次调用的时候还需转换一下,如果使用classmethod或者staticmethod 就不需要再bound,略微可以提高效率。

Desciptor

  1. __get__(self, instance, owner)
  2. __set__(self, instance, value)
  3. __delete__(self, instance)
  4. __set_name__(self, owner, name)

一般定义在类对象中,当类dict中的一个attribute为实现了上述任一方法的对象时,称attribute为一个descriptor,该descriptor的owner是该类

当x为类A的一个Descriptor(位于字典中),a 为A的一个对象,则以实现了__get__的Descriptor为例:

  • 实例对象访问:a.x 等价于 A.__dict__['x'].__get__(a, A)
  • 类对象访问:A.x 等价于 A.__dict__['x'].__get__(None, A) . instance 为 None
  • 对于没有实现__get__的descriptor,在访问到的时候和正常属性访问一样,返回该Descriptor本身

data descriptor

实现了__get__和__set__, 当实例对象的dict中有同名属性的时候,此时该descriptor优先级更高

nondata descriptor

只实现了__get__, 当实例对象的__dict__中有同名属性的时候,此时__dict__中的属性优先级更高

  • 是否是data descriptor是针对属性获取而言,区别在于属性获取的时候descriptor优先级是否比dict中的属性高
  • 而对于属性赋值而言,实现了__set__的descriptor的优先级总是比dict里的属性高.(当然setattr优先级最高)
  • 由此,让一个属性只可读,可以使用data descriptor, 让set raise一个AttributeError

Examples

实际上,python实现的调用方法时的对象绑定,classmethod, staticmethod都是使用Descriptor实现的。他们都是在C语言中实现的,但是可以用pure python的形式实现:

  1. # types.py
  2. class _C:
  3. def _m(self): pass
  4. MethodType = type(_C()._m)
  5. # 绑定方法的另一个方法为使用partial
  6. # instance methods: non-data descriptor
  7. class Function(object):
  8. . . .
  9. def __get__(self, obj, objtype=None):
  10. "Simulate func_descr_get() in Objects/funcobject.c"
  11. if obj is None:
  12. return self
  13. # 用于绑定对象
  14. return types.MethodType(self, obj)
  15. # staticmethod(): non-data descriptor
  16. class StaticMethod(object):
  17. "Emulate PyStaticMethod_Type() in Objects/funcobject.c"
  18. def __init__(self, f):
  19. self.f = f
  20. def __get__(self, obj, objtype=None):
  21. return self.f
  22. # classmethod(): non-data descriptor
  23. class ClassMethod(object):
  24. "Emulate PyClassMethod_Type() in Objects/funcobject.c"
  25. def __init__(self, f):
  26. self.f = f
  27. def __get__(self, obj, klass=None):
  28. if klass is None:
  29. klass = type(obj)
  30. def newfunc(*args):
  31. return self.f(klass, *args)
  32. return newfunc
  33. # property(): 是一个data descriptor
  34. class Property(object):
  35. "Emulate PyProperty_Type() in Objects/descrobject.c"
  36. def __init__(self, fget=None, fset=None, fdel=None, doc=None):
  37. self.fget = fget
  38. self.fset = fset
  39. self.fdel = fdel
  40. if doc is None and fget is not None:
  41. doc = fget.__doc__
  42. self.__doc__ = doc
  43. def __get__(self, obj, objtype=None):
  44. if obj is None:
  45. return self
  46. if self.fget is None:
  47. raise AttributeError("unreadable attribute")
  48. return self.fget(obj)
  49. def __set__(self, obj, value):
  50. if self.fset is None:
  51. raise AttributeError("can't set attribute")
  52. self.fset(obj, value)
  53. def __delete__(self, obj):
  54. if self.fdel is None:
  55. raise AttributeError("can't delete attribute")
  56. self.fdel(obj)
  57. def getter(self, fget):
  58. return type(self)(fget, self.fset, self.fdel, self.__doc__)
  59. def setter(self, fset):
  60. return type(self)(self.fget, fset, self.fdel, self.__doc__)
  61. def deleter(self, fdel):
  62. return type(self)(self.fget, self.fset, fdel, self.__doc__)

Container

__len__(self):
用于 len(obj)
__getitem__(self, key):
用于 obj[key]
__setitem__(self, key, value):
用于 obj[key] = value
__delitem__(self, key):
用于 del obj[key]
__missing__(self, key):
一般用于在getitem中找不到后调用该方法进行处理
__reversed__(self):
用于 reversed()调用。需要返回一个 iterator。
当reversed未实现时,会使用__len__和__getitem__进行模拟。
__contains__(self, item):
用于 in 操作。当__contains__未实现时,会尝试使用__iter__,如果还是未实现则会使用__getitem__

Iterable/Iterator

属于一种概念,并不是特定的对象类型. 一个对象满足Iterable的要求需要实现两个方法:

  • __iter__() 需要返回一个Iterator
  • __next__() 每次调用返回一个值,最后一次返回Stopiteration.

__iter__(self)
供内置函数iter(),for, in 使用,需要返回一个iterator 即实现了next()。
一般返回的可迭代对象是 self, 其同时也实现了__next__()方法.
注意这个函数可以是一个生成器函数(yield):

  • 当generator function 被调用的时候,返回的是一个generator object,每次调用所返回的都是全新的generator
  • 而一个generator由于实现了next()方法,自然是一个iterator

iter(obj, till)
调用对象的__iter__()方法。如果没有iter()方法,那么该对象必须实现__getitem__()方法
till 表示不停调用next()方法,获取各项,直到遇到till后停止

__next__(self)
使得该类对象变为可迭代对象(iterator),每次迭代时会调用此方法获取值(return), 如果没有元素了,需要raise StopIteration
因此要想一个类可迭代必须要实现__next__方法,__iter__不是必须的
注意里面不要使用yield, 这样相当于每次调用都返回一个generator,

next(iterator)
调用对象的__next__()方法

解包

  1. a, b, c = iter([1, 2, 3])
  2. 1 in iter([1, 2, 3])
  3. 4 not in iter([1, 2, 3])

Iterable

python解释器在迭代(指代for类似的操作)的时候,都会自动运行iter,再接着调用__next__
当一个对象没有实现iter但是实现了getitem的时候,则创建一个迭代器并返回,每次迭代的时候都会调用迭代器的getitem_方法。
如果即没有iter也没有getitem,则抛出TypeError异常
所以检验一个对象是否是迭代器可以用:

  1. try:
  2. iter(obj)
  3. except TypeError:
  4. do something
  5. for i in x:
  6. pass
  7. # x 必须要是一个__iter__方法返回一个iterator的对象
  8. a = [1, 2 ,3]
  9. for i in a:
  10. pass
  11. # 其实是等价于:
  12. for i in iter(a):
  13. pass

Generator

包含yield语句的callable对象。
generator可以suspend/resume函数调控运行,还可以send/yield传递数据
Generator function 调用返回的generator object实现了 Iterator 的要求, 即:

  • 实现了__iter__, 返回其自身self
  • 实现了__next__,每次调用next等价于使用send(None)所yield的值
  • 最后一次next调用send(None),生成器return 抛出StopIteration

Context Manager

  • 使用类:
    __enter__()
    __exit__(self, exec_type, exec_value, traceback)
    当离开该 context 时无异常,则后三个参数的值都为 None
  • 使用 generator
  1. from contextlib import contextmanager
  2. @contectmanager
  3. def custom_open(filename):
  4. f = open(filename)
  5. try:
  6. yield f
  7. finally:
  8. f.close()
  9. with custom_open('file') as f:
  10. contents = f.read()

使用yield返回,赋值给f,当with语句块结束时,重启生成器,执行finally 语句块。
猜测也是包装成了一个拥有__enter__, __exit__的类:

  • 当__enter__后,send(None)启动生成器获取值
  • 当__exit__后,再send(),生成器执行完所有语句后 raise StopIteration

Asyncio

Internal

  • 外层的eventloop使用的是epoll事件循环
  • asyncio的基本流程为
    • 使用Future包装所有异步非阻塞IO操作,在一个generator中通过yield from,yeid嵌套多个异步操作,整个generator使用Task对象进行包装,Task会不断的调用send进行resume generator的运行
    • 当Task运行时,generator在某个点上执行,yield 出 Future,该Future在eventloop注册了IO事件的Future.set_result的回调函数
    • Eventloop监听到事件,调用set_result函数,set_result函数会进行阻塞IO读/写操作,之后会调用Future内注册的done_callbacks,其中一个函数就是Task的step函数,该函数内调用send resume generator的运行
  • async/ await只不过是语法糖,用于区分一般的生成器和协程,最内层都是调用的generator的yield/send函数

Functional programming

Functional programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell.

Functions that have no side effects at all are called purely functional. Every function’s output must only depend on it’s input.

Builtin functions:

  • map/filter/iter
  • list comprehensions / generator comprehensions

  1. ( expression for expr1 in sequence1
  2. if condition1
  3. for expr2 in sequence2
  4. if condition2
  5. for expr3 in sequence3 ...
  6. if condition3
  7. for exprN in sequenceN
  8. if conditionN )
  9. # equals to:
  10. for expr1 in sequence1:
  11. if not (condition1):
  12. continue
  13. for expr2 in sequence2:
  14. if not (condition2):
  15. continue
  16. ...
  17. for exprN in sequenceN:
  18. if not (conditionN):
  19. continue

Itertools

Creating new iterators:

count(start, [step]) creating an endless iterator emiting items start from start.

cycle(iter) creating an endless iterator from iter.

repeat(item, [n]) creating an iterator emmiting item for n time. n is None means endless.

chain(iter1, iter2 …… itern) creating an iterator chains all iterators in arguments.

islice(iter, [start], stop, [step]) creating an iterator emit elements within that slice region. Don’t support negative value for start, stop and step.

tee(iter, [N]) similar to tee in unix, return n replicate iterators of the input iterator. default n is 2.

Calling functions on elements:

starmap(func, iter) It assumes every element emited by iter is a tuple, And will pass this tuple to func as it’s arguments.

Selecting elements:

filterfalse(predicate, iter) The opposite of filter, return an iterrator emiting elements in iter with a False value returned by calling predicate

takewhile(predicate, iter) return an iterator with elements for as long as the predicate returns True. i.e. Elements before the first element with False value.

dropwhile(predicate, iter) discards elements while the predicate returns true, and then returns an iterrator emiting the rest of the elements.

compress(data, selectors) receives two iterators, and return an iterator with elements in data that the correspoding element in selector is True.

Combinatoric functions:

combinations(iter, r) return an iterator emiting all possible r-tuple combinations of the elements contained in iterable.

combinations_with_replacement(iter, r) elements can be repeated within a single tuple.

permutaions(iter, r=None) permutaions. if r is None, returned tuple’s length equals to number of elements in iter.

Grouping elements:

groupby(iter, key_func=None) return an iterator of 2-tuples containing a key value and an iterator for the elements with that key.

Elements should by already sorted based on the keyfunc, and the returned iteratores use the underlying input iterator,

So the iterator in the first tuple should be consumed before requesting the second 2-tuple.

Functools module:

partial(func, arg1 , kwargsn=valuen)

reduce(func, iter, [initial_value]) This function is often coorperated with operator.add, operator.concat as the func argument.

itertools.accumulate(iterable, func) Instead of returning the results of the last function call, this function will return an iterator

emiting results of every step.

Operator module:

containing a set of functions corresponding to python’s operators.

math: add() sub() mul() floordiv() abs()

logical: not*() truth()

bitwise: and() or() invert()

comparison: eq() ne() lt() le() gt() ge()

identity: is*() is_not()

other: itemgetter attrgetter methodcaller

Examples:

from collections import namedtuple

from operator import itemgetter, attrgetter, methodcaller

Feature = namedtuple(‘Feature’, ‘hieght weight’)

Human = namedtuple(‘Person’, ‘name age features’)

man = Human(‘qzhong’, 19, Feature(163, 115))

a =( 1, 2, 3, 4)

s = “asdas,dsqwe”

attrgetter(‘name’, ‘features.height’)(man) -> (‘qzhong’, 163)

itemgetter(1 ,3, 1, 0)(a) -> (2, 4, 2, 1)

methodcaller(‘upper’)(s) -> “ASDAS,DSQWE”

methodcaller(‘replace’, ‘, ‘, ‘’) -> “asdasdsqwe”

itemgetter 调用的是对象的getitem方法

attrgetter 调用的是 getattr()

itemgetter 和 attrgetter 都支持对多个下标或者属性进行访问,返回的就是一个元组,否则返回 return 的值

attrgetter 还支持多个层级的属性访问

Closures:

Closure 就是一个函数绑定了 nonlocal 的变量,即使这个 nonlocal 变量所在的作用域已经消失了

def deco(f):

deco.name = 1

a = 1

def inner(args, *kwargs):

print(a)

return f(args, *kwars)

return inner

a = deco()

a.closure -> (,)

a.closure[0] -> b.closure[0].cell_contents

b.code.co_names -> (‘print’,)

b.code.co_freevars -> (‘a’,)

返回的 inner 拥有一个closures属性,里面包含了闭包所引入的各种外部变量或者说 free variable

从上面也可以看出,函数同样是 object,拥有一系列 state

注意上面的 deco.name, 给 deco 的字典里添加了一个新的元素 name,值为 1

注意报错的情况:

Eaxmple1:

b = 3

def f1(a):

print(a)

print(b)

b = 3

def f1(a): print(a)

print(b) -> Unbound error

b = 3

第一次不报错,因为编译函数成字节码的时候,b 不存在赋值语句,所以将 b 看成是 global 变量

在函数运行的时候,从 global 中导入 b,导入成功成功

第二次报错,因为编译函数成字节码的时候,发现 b 存在赋值语句,所以将 b 看成是 local 变量

在函数运行的时候,从 local 中导入 b,而 local 中还没有 b 这个变量,所以报错

Example2:

def make_averager():

count = 0

total = 0

my_li = []

def averager(new_value):

my_li.append(1) -> No error

count += 1 -> Unbound error

total += new_value

return total / count

return averager

第一个语句不报错是因为在这个函数里面 my_li 没有发生过赋值语句,所以将 my_li 看成是 non_local 的变量

函数运行的时候,成功从外部作用域中导入 my_Li

第二个语句报错是因为 count += 1 等价于 count = count + 1, 因此是赋值语句,所以将 count 看成是 local 变量

但是当执行 count = count + 1 时,先执行右边的语句,从 local 中导入 count,而此时 local 中并没有 count,所以报错

上述两个问题的解决办法为分别使用 global 和 nonlocal 声明,告诉 VM 这两个变量就是 global 变量和 nonlocal 变量

Decorator:

Decorator 就使用到了 closure,因为要将外部变量 func 引入到 return 的 func 中

任何返回一个 callable 对象的 callable 对象都可以作为一个装饰器

@deco

def a():

pass

等价于

a = deco(a)

a -> main.deco..inner

a.name -> inner

注意使用装饰器的时候,在本命名空间中,将装饰器返回的函数赋值给了被装饰的函数的名字

注意一个变量的名字和其name不是等价的, 被装饰的函数其在装饰器内部的 locals()命名空间中

保留被装饰函数的 metadata 信息:

使用 functools.wrap

WRAPPER_ASSIGNMENTS = (‘module‘, ‘name‘, ‘qualname‘, ‘doc‘,

‘annotations‘)

WRAPPER_UPDATES = (‘dict‘,)

def update_wrapper(wrapper,

wrapped,

assigned = WRAPPER_ASSIGNMENTS,

updated = WRAPPER_UPDATES):

for attr in assigned:

try:

value = getattr(wrapped, attr)

except AttributeError:

pass

else:

setattr(wrapper, attr, value)

for attr in updated:

getattr(wrapper, attr).update(getattr(wrapped, attr, {}))

wrapper.wrapped = wrapped

return wrapper

def wraps(wrapped,

assigned = WRAPPER_ASSIGNMENTS,

updated = WRAPPER_UPDATES):

return partial(update_wrapper, wrapped=wrapped,

assigned=assigned, updated=updated)

这个函数会保留被装饰函数的module, name, qualname, doc, annotations

以及被装饰函数中_dict中的内容

使用 decorator 的一个例子就是用来注册一些函数,比如 flask 中用来注册 view

Decorators in standard library:

@property

@classnmethod

@staticmethod

@functools.wrap

@functools.singledispatch

@functools.total*ordering

Automatically make comparison methods from two methods.

@functools.lru_cache(maxsize=4, typed=False)

used to memoizing maxsize most recent calls.

maxsize should be a power of 2.

Uses positional and keyword arguments as the building part of the key stored in a dict

Thus all arguments should be hashable

@functools.singledispatch

despatch methods based on type of the first argument in a flexible and moduled way.

class A():

@singledispatch

def htmlsize(obj):

pass

@htmlsize.register(str)

def *(text):

pass

@htmlsize.register(tuple)

@htmlsize.register(abc.MutableSequence)

def _(seq): pass

实例:

通过动态创建类,模拟 named tuple:

import operator

import types

import sys

def named_tuple(classname, fieldnames): # Populate a dictionary of field property accessors

cls_dict = { name: property(operator.itemgetter(n))

for n, name in enumerate(fieldnames) }

  1. # Make a __new__ function and add to the class dict
  2. def __new__(cls, *args):
  3. if len(args) != len(fieldnames):
  4. raise TypeError('Expected {} arguments'.format(len(fieldnames)))
  5. return tuple.__new__(cls, args)
  6. cls_dict['__new__'] = __new__
  7. # Make the class
  8. cls = types.new_class(classname, (tuple,), {},
  9. lambda ns: ns.update(cls_dict))
  10. # Set the module to that of the caller
  11. cls.__module__ = sys._getframe(1).f_globals['__name__']
  12. return cls

operator.itemgetter(n)返回的是一个 callable 对象,接受的唯一个参数是要使用getitem的对象

在 property 中,访问这个 property 的时候自动将相应的对象作为第一个参数,并调用。

cls.module = sys._getframe(1).f_globals[‘name‘] 用以获取正确的模块名

通过元类,模拟 named tuple:

import operator

class StructTupleMeta(type):

def init(cls, args, *kwargs):

super().init(args, *kwargs)

for n, name in enumerate(cls._fields):

setattr(cls, name, property(operator.itemgetter(n)))

class StructTuple(tuple, metaclass=StructTupleMeta):

_fields = []

def new(cls, *args):

if len(args) != len(cls._fields):

raise ValueError(‘{} arguments required’.format(len(cls._fields)))

return super().new(cls, args)

这里注意在 super().new中调用 tuple.new方法,tuple 的构造函数接受一个参数,所以需要把参数的数组传递给它

避免重复的 property 方法:

def typed*property(name, expected_type):

storage_name = ‘*’ + name

  1. @property
  2. def prop(self):
  3. return getattr(self, storage_name)
  4. @prop.setter
  5. def prop(self, value):
  6. if not isinstance(value, expected_type):
  7. raise TypeError('{} must be a {}'.format(name, expected_type))
  8. setattr(self, storage_name, value)
  9. return prop

Example use

class Person:

name = typed_property(‘name’, str)

age = typed_property(‘age’, int)

  1. def __init__(self, name, age):
  2. self.name = name
  3. self.age = age

from functools import partial

String = partial(typed_property, expected_type=str)

Integer = partial(typed_property, expected_type=int)

Example:

class Person:

name = String(‘name’)

age = Integer(‘age’)

  1. def __init__(self, name, age):
  2. self.name = name
  3. self.age = age

其中 typed_property 返回的是一个实现了get和set的 descriptor

这个与直接在类定义里面直接写函数加 property 类似

但是它通过闭包使得 property 对象可以访问到一些预定义的数据,

并且省去了写重复的代码

当然也可以将要访问的数据 name 以 property 对象属性的方式放在 property 对象的字典中

但通过使用闭包,免去了写 decriptor 类的开销

IO:

IOBase -> RawIOBase -> FileIO

-> BufferedIOBase -> BytesIO

-> BufferedReader

-> BufferedWriter

-> BufferedRandom

-> BufferedRWPair

-> TextIOBase -> TextIOWrapper

-> StringIO

RawIOBase(abstract)

FileIO(name, mode=’r’, closefd=True, opener=None):

FileIO represents an OS-level file containing bytes data.

BufferedIOBase(abstract)

uses in-memory buffering method . Underlying raw stream is a RawIOBase instance

uses a RawIOBase instance as underlying stream.

normally is a FileIO

BytesIO([initial_bytes])

A steam implementaion using an in-memory bytes buffer

getbuffer() return a readable and writable view over the contenst of the buffer.

getvalue() return bytes contaning the entire contents of the buffer.

BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffer providing higher-level acces to a readable, sequential RawIOBase, When reading data

from this object, a larger data may be requesting and kept in an internal buffer.

BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)

Similar with BufferedReader. write data into a RawIOBase instance.

When writing data to this object, data is placed into an internal buffer. The data will be written out to the

underlying RawIOBase object under various conditions:

when buffer gets too small for all pending data.

when flush() is called.

when a seek() is requested(for BufferedRandom objects)

when the BufferedWriter object is closed or destroyed.

flush() Force bytes held in the buffer into the raw stream.

BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered interface to random access streams.

BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered object combining two unidirectional RawIOBase objects. one readable and the other writable.

(BufferedRandom uses only one two-directional RawIOBase objects.)

TextIOBase(abstract)

uses a BufferedIOBase isntance as underlying stream.

is a BufferedReader when using r mode in subclass

is a BufferedWriter when uisng w mode in subcalss

is a BufferedRandom when useing w+ or ….

…..

encoding

errors

newlines

buffer The undelying binary buffer(A BufferedIOBase instance)

TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)

Implement a Text stream.

StringIO(initial_value=’’, newline=’\n’)

An in-memory stream for text I/O.

Eaxmple:

a = open(‘1’, ‘r’)

a -> TextIOWrapper

a.buffer -> BufferedReader

a.buffer.raw -> FileIO

b = open(‘2’, ‘wb+’)

b -> BufferedRandom

b.raw -> FileIO

Perforamance:

BufferedIO is fast enough.

TextIO is much slower than bufferedIO because of the conversion from bytes to unicode string.

StringIO/BytesIO’s speed are similar as they are both in-memory.

BufferedIO and FileIO are thread-safe

console

Unexpected reference:

_ reference the last u nbound results(not None) of the expression

list(my_list) my_list[:] create a copy

tuple(my_tuple) my_tuple[:] create a reference

format format

del 将该对象的引用计数减一

当对象的引用计数为 0 时,才会调用对象的class.del




py3
keyword only parameter
positional-only parameter def show(name, age, *args, home=”asdas”): home must be specified


sorted 没有cmp参数了

qualname

exception chaining


inspect.getattr_statis
不会执行property的call函数


annotation
lamba doesn’t support

py3.7
dataclass 用于替代namedtuple

py 3.8

volnut operator

if (n := len(a)):
return

format

print(f”{message=}”)
等价于
print(f”message={message}”)

pep582
package management
site.py
pypi packaging package

package install demo
fetch link in pypi.org
download whl file
fecth meta data in whl file
fetch dependency list in whl file
use pip install all packages without dependency option

pep517
pyproject.toml

web app 压力测试
apache jmeter

init.py
用于标注一个python (sub)package, import该package的时候会运执行该文件
该文件内
from .module import var
.module表示当前package的module

main适用于区分一个module是否是主程序,只有一个py文件(module)真正的作为一个module被导入的时候,该py文件内的name才会是该文件的名字,表示是一个module

main.py
用于作为可执行package的入口,没有该文件则该package不可执行
python -m package会执行main.py
from . import module
.表示该package,所以会调用该package的init.py

main__ 为module名字,
当python a.py的时候,
name == “main“,
当python -m package的时候,
name == “main“, 会自动在执行main.py之前执行_init.py