deff(x):forkinrange(10000000):x*x*x/x+x+x+x+xreturnxx=2# Reuse a value that's expensive to compute
%timeit[y:=f(x),y**2,y**3]# Without reuse
%timeit[f(x),f(x)**2,f(x)**3]
1.78 s ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
5.45 s ± 93.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
importmultiprocessingfrommultiprocessing.managersimportSharedMemoryManager# Arbitrary operations on a shared list
defdo_work(shared_list,start,stop):foridxinrange(start,stop):shared_list[idx]=1# Example from the docs
withSharedMemoryManager()assmm:sl=smm.ShareableList(range(2000))# Divide the work among two processes, storing partial results in sl
p1=multiprocessing.Process(target=do_work,args=(sl,0,1000))p2=multiprocessing.Process(target=do_work,args=(sl,1000,2000))p1.start()p2.start()# A multiprocessing.Pool might be more efficient
p1.join()p2.join()# Wait for all work to complete in both processes
total_result=sum(sl)# Consolidate the partial results now in sl
# `do_work` set all values to 1 in parallel
print(f"Total of values in shared list: {total_result}")
# scripts/valid_589.py
fromtypingimportTypedDictclassMovie(TypedDict):name:stryear:int# Cannonical assignment of Movie
movie:Movie={'name':'Wally 2: Rise of the Garbage Bots','year':2055}
mypy不会出现任何问题,因为字典是某种类型的有效实现。
!mypyscripts/valid_589.py
[1m[32mSuccess: no issues found in 1 source file[m
scripts/invalid_values_589.py:10: [1m[31merror:[m Incompatible types (expression has type [m[1m"str"[m, TypedDict item [m[1m"year"[m has type [m[1m"int"[m)[m
scripts/invalid_values_589.py:10: [1m[31merror:[m Incompatible types (expression has type [m[1m"int"[m, TypedDict item [m[1m"name"[m has type [m[1m"str"[m)[m
[1m[31mFound 2 errors in 1 file (checked 1 source file)[m
3.8 版本还将实现最终性。我们可以阻止对象被重写或继承。@final装饰器可以与定义一起使用class来阻止继承,而Final类型可以阻止重写。以下是 PEP 中的两个示例:
# Example 1, inheriting a @final class
fromtypingimportfinal@finalclassBase:...classDerived(Base):# Error: Cannot inherit from final class "Base"
...# Example 2, overriding an attribute
fromtypingimportFinalclassWindow:BORDER_WIDTH:Final=2.5...classListView(Window):BORDER_WIDTH=3# Error: can't override a final attribute