SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Downloaden Sie, um offline zu lesen
Commit ускоривший
Python 2.7 на 30%
и
новое в Python 3.5
sapronov.alexander92@gmail.com
@sapronovalex92
pynsk.nsk@gmail.com
vk.com/pynsk
facebook.com/PyNskCom
@py_nsk
Александр Сапронов:
Python 2.7.11
Vamsi Parasa of the Server Scripting Languages Optimization team at Intel posted
a patch to change the switch statement that executes Python bytecode in the
CPython interpreter to use computed gotos instead.
(http://article.gmane.org/gmane.comp.python.devel/153401)
Python 2.7.11
Vamsi Parasa of the Server Scripting Languages Optimization team at Intel posted
a patch to change the switch statement that executes Python bytecode in the
CPython interpreter to use computed gotos instead.
(http://article.gmane.org/gmane.comp.python.devel/153401)
computed goto
В отличие от switch-case: Не производит граничных проверок
#define OP_HALT 0x0
#define OP_INC 0x1
int interp_switch(unsigned char* code, int initval) {
int pc = 0;
int val = initval;
while (1) {
switch (code[pc++]) {
case OP_HALT:
return val;
case OP_INC:
val++;
break;
default:
return val;
}
}
}
computed goto
В отличие от switch-case: Не производит граничных проверок
#define OP_HALT 0x0
#define OP_INC 0x1
int interp_switch(unsigned char* code, int initval) {
int pc = 0;
int val = initval;
while (1) {
switch (code[pc++]) {
case OP_HALT:
return val;
case OP_INC:
val++;
break;
default:
return val;
}
}
}
int interp_cgoto(unsigned char* code, int initval) {
static void* dispatch_table[] = {&&do_halt, &&do_inc};
#define DISPATCH() goto *dispatch_table[code[pc++]]
int pc = 0;
int val = initval;
DISPATCH();
while (1) {
do_halt:
return val;
do_inc:
val++;
DISPATCH();
}
}
computed goto
В отличие от switch-case: CPU может лучше прогнозировать ветвления
Подробно про computed goto:
http://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables
Модуль предсказания переходов:
устройство, входящее в состав микропроцессоров, имеющих
конвейерную архитектуру, предсказывающее, будет ли
выполнен условный переход в исполняемой программе.
Новое в Python 3.5 - PEP 478
● PEP 441 , improved Python zip application support
● PEP 448 , additional unpacking generalizations
● PEP 461 , "%-formatting" for bytes and bytearray objects
● PEP 465 , a new operator ("@") for matrix multiplication
● PEP 471 , os.scandir(), a fast new directory traversal function
● PEP 475 , adding support for automatic retries of interrupted system calls
● PEP 479 , change StopIteration handling inside generators
● PEP 484 , the typing module, a new standard for type annotations
● PEP 485 , math.isclose(), a function for testing approximate equality
● PEP 486 , making the Widnows Python launcher aware of virtual environments
● PEP 488 , eliminating .pyo files
● PEP 489 , a new and improved mechanism for loading extension modules
● PEP 492 , coroutines with async and await syntax
PEP 448 - additional unpacking generalizations
>>> print(*[1], *[2], 3)
1 2 3
>>> dict(**{'x': 1}, y=2, **{'z': 3})
{'x': 1, 'y': 2, 'z': 3}
>>> *range(4), 4
(0, 1, 2, 3, 4)
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {*range(4), 4}
{0, 1, 2, 3, 4}
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
>>> {'x': 1, **{'x': 2}}
{'x': 2}
>>> {**{'x': 2}, 'x': 1}
{'x': 1}
PEP 484 - the typing module, a new standard
for type annotations
def greeting(name: str) -> str:
return 'Hello ' + name
from typing import *
T = TypeVar('T')
def filter(function: Optional[Callable[[T], Any]],
iterable: Iterable[T]) -> Iterator[T]:
...
Было
Стало
PEP 492 - coroutines with async and await syntax
async def read_data(db):
pass
async def read_data(db):
data = await db.fetch('SELECT ...')
Новые ключевые слова:
async и await
11
sapronov.alexander92@gmail.com
@sapronovalex92
pynsk.nsk@gmail.com
vk.com/pynsk
facebook.com/PyNskCom
@py_nsk
PyNSK контакты: Мои контакты:
ru.linkedin.com/in/alexsapronov
Питоны кончились…
Вопросы?

Weitere ähnliche Inhalte

Was ist angesagt?

우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고
용 최
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
maruyama097
 

Was ist angesagt? (20)

우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고우분투한국커뮤니티 수학스터디결과보고
우분투한국커뮤니티 수학스터디결과보고
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Alias
AliasAlias
Alias
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Python 3000
Python 3000Python 3000
Python 3000
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Python tour
Python tourPython tour
Python tour
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1
 
エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理エンタープライズ・クラウドと 並列・分散・非同期処理
エンタープライズ・クラウドと 並列・分散・非同期処理
 
Day3
Day3Day3
Day3
 

Andere mochten auch

Andere mochten auch (6)

Магия в Python: Дескрипторы. Что это?
Магия в Python: Дескрипторы. Что это?Магия в Python: Дескрипторы. Что это?
Магия в Python: Дескрипторы. Что это?
 
Мир Python функционалим с помощью библиотек
Мир Python  функционалим с помощью библиотекМир Python  функционалим с помощью библиотек
Мир Python функционалим с помощью библиотек
 
Получаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работаетПолучаем текст веб-страниц из Python и как это работает
Получаем текст веб-страниц из Python и как это работает
 
Python инструменты решения типичных задач
Python  инструменты решения типичных задачPython  инструменты решения типичных задач
Python инструменты решения типичных задач
 
Интерфейсы в Python
Интерфейсы в PythonИнтерфейсы в Python
Интерфейсы в Python
 
Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?
 

Ähnlich wie Commit ускоривший python 2.7.11 на 30% и новое в python 3.5

What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
mfrancis
 

Ähnlich wie Commit ускоривший python 2.7.11 на 30% и новое в python 3.5 (20)

Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
 
Python Evolution
Python EvolutionPython Evolution
Python Evolution
 
Python 3.6 Features 20161207
Python 3.6 Features 20161207Python 3.6 Features 20161207
Python 3.6 Features 20161207
 
Joblib: Lightweight pipelining for parallel jobs (v2)
Joblib:  Lightweight pipelining for parallel jobs (v2)Joblib:  Lightweight pipelining for parallel jobs (v2)
Joblib: Lightweight pipelining for parallel jobs (v2)
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python
 
Python Interview Questions And Answers 2019 | Edureka
Python Interview Questions And Answers 2019 | EdurekaPython Interview Questions And Answers 2019 | Edureka
Python Interview Questions And Answers 2019 | Edureka
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Python Orientation
Python OrientationPython Orientation
Python Orientation
 
Beating Python's GIL to Max Out Your CPUs
Beating Python's GIL to Max Out Your CPUsBeating Python's GIL to Max Out Your CPUs
Beating Python's GIL to Max Out Your CPUs
 
Faster Python Programs Through Optimization by Dr.-Ing Mike Muller
Faster Python Programs Through Optimization by Dr.-Ing Mike MullerFaster Python Programs Through Optimization by Dr.-Ing Mike Muller
Faster Python Programs Through Optimization by Dr.-Ing Mike Muller
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
 
What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
What’s cool in the new and updated OSGi specs (DS, Cloud and more) - C Ziegel...
 
Last train to php 7
Last train to php 7Last train to php 7
Last train to php 7
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
What's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | EdurekaWhat's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | Edureka
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
 
What We Learned Building an R-Python Hybrid Predictive Analytics Pipeline
What We Learned Building an R-Python Hybrid Predictive Analytics PipelineWhat We Learned Building an R-Python Hybrid Predictive Analytics Pipeline
What We Learned Building an R-Python Hybrid Predictive Analytics Pipeline
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Python 3000
Python 3000Python 3000
Python 3000
 

Mehr von PyNSK

Mehr von PyNSK (20)

Нейронные сети и Keras. Часть 1
Нейронные сети и Keras. Часть 1Нейронные сети и Keras. Часть 1
Нейронные сети и Keras. Часть 1
 
Нейронные сети и Keras. Часть 2
Нейронные сети и Keras. Часть 2Нейронные сети и Keras. Часть 2
Нейронные сети и Keras. Часть 2
 
Asyncio для процессинга распределенной базы данных
Asyncio для процессинга  распределенной базы данныхAsyncio для процессинга  распределенной базы данных
Asyncio для процессинга распределенной базы данных
 
Python для GameDev
Python для GameDevPython для GameDev
Python для GameDev
 
Python инструменты для нагрузочного тестирования
Python инструменты для нагрузочного тестированияPython инструменты для нагрузочного тестирования
Python инструменты для нагрузочного тестирования
 
Python, Django и корпоративные информационные системы
Python, Django и корпоративные информационные системыPython, Django и корпоративные информационные системы
Python, Django и корпоративные информационные системы
 
Настрой контент под пользователя!
Настрой контент под пользователя!Настрой контент под пользователя!
Настрой контент под пользователя!
 
Питон в малине
Питон в малинеПитон в малине
Питон в малине
 
Мой Python всегда со мной!
Мой Python всегда со мной!Мой Python всегда со мной!
Мой Python всегда со мной!
 
Как и зачем можно создать DSL на Python
Как и зачем можно создать DSL на PythonКак и зачем можно создать DSL на Python
Как и зачем можно создать DSL на Python
 
Во внутренности Kivy
Во внутренности KivyВо внутренности Kivy
Во внутренности Kivy
 
Зоопарк python веб-фреймворков
Зоопарк python веб-фреймворковЗоопарк python веб-фреймворков
Зоопарк python веб-фреймворков
 
Как Python Дайджест работает с внешней статикой
Как Python Дайджест работает с внешней статикойКак Python Дайджест работает с внешней статикой
Как Python Дайджест работает с внешней статикой
 
Применение behave+webdriver для тестирования Web-проектов
Применение behave+webdriver для тестирования Web-проектовПрименение behave+webdriver для тестирования Web-проектов
Применение behave+webdriver для тестирования Web-проектов
 
Ctypes в игровых приложениях на python
Ctypes в игровых приложениях на pythonCtypes в игровых приложениях на python
Ctypes в игровых приложениях на python
 
Оптимизация производительности Python
Оптимизация производительности PythonОптимизация производительности Python
Оптимизация производительности Python
 
JSON-RPC или когда rest неудобен
JSON-RPC или когда rest неудобенJSON-RPC или когда rest неудобен
JSON-RPC или когда rest неудобен
 
TestRail. Некоторые возможности интеграции.
TestRail. Некоторые возможности интеграции.TestRail. Некоторые возможности интеграции.
TestRail. Некоторые возможности интеграции.
 
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST""Модифицируй это!" или "Больше магии Python с помощью изменения AST"
"Модифицируй это!" или "Больше магии Python с помощью изменения AST"
 
Быстрый старт в gDrive API
Быстрый старт в gDrive APIБыстрый старт в gDrive API
Быстрый старт в gDrive API
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Commit ускоривший python 2.7.11 на 30% и новое в python 3.5

  • 1. Commit ускоривший Python 2.7 на 30% и новое в Python 3.5 sapronov.alexander92@gmail.com @sapronovalex92 pynsk.nsk@gmail.com vk.com/pynsk facebook.com/PyNskCom @py_nsk Александр Сапронов:
  • 2. Python 2.7.11 Vamsi Parasa of the Server Scripting Languages Optimization team at Intel posted a patch to change the switch statement that executes Python bytecode in the CPython interpreter to use computed gotos instead. (http://article.gmane.org/gmane.comp.python.devel/153401)
  • 3. Python 2.7.11 Vamsi Parasa of the Server Scripting Languages Optimization team at Intel posted a patch to change the switch statement that executes Python bytecode in the CPython interpreter to use computed gotos instead. (http://article.gmane.org/gmane.comp.python.devel/153401)
  • 4. computed goto В отличие от switch-case: Не производит граничных проверок #define OP_HALT 0x0 #define OP_INC 0x1 int interp_switch(unsigned char* code, int initval) { int pc = 0; int val = initval; while (1) { switch (code[pc++]) { case OP_HALT: return val; case OP_INC: val++; break; default: return val; } } }
  • 5. computed goto В отличие от switch-case: Не производит граничных проверок #define OP_HALT 0x0 #define OP_INC 0x1 int interp_switch(unsigned char* code, int initval) { int pc = 0; int val = initval; while (1) { switch (code[pc++]) { case OP_HALT: return val; case OP_INC: val++; break; default: return val; } } } int interp_cgoto(unsigned char* code, int initval) { static void* dispatch_table[] = {&&do_halt, &&do_inc}; #define DISPATCH() goto *dispatch_table[code[pc++]] int pc = 0; int val = initval; DISPATCH(); while (1) { do_halt: return val; do_inc: val++; DISPATCH(); } }
  • 6. computed goto В отличие от switch-case: CPU может лучше прогнозировать ветвления Подробно про computed goto: http://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables Модуль предсказания переходов: устройство, входящее в состав микропроцессоров, имеющих конвейерную архитектуру, предсказывающее, будет ли выполнен условный переход в исполняемой программе.
  • 7. Новое в Python 3.5 - PEP 478 ● PEP 441 , improved Python zip application support ● PEP 448 , additional unpacking generalizations ● PEP 461 , "%-formatting" for bytes and bytearray objects ● PEP 465 , a new operator ("@") for matrix multiplication ● PEP 471 , os.scandir(), a fast new directory traversal function ● PEP 475 , adding support for automatic retries of interrupted system calls ● PEP 479 , change StopIteration handling inside generators ● PEP 484 , the typing module, a new standard for type annotations ● PEP 485 , math.isclose(), a function for testing approximate equality ● PEP 486 , making the Widnows Python launcher aware of virtual environments ● PEP 488 , eliminating .pyo files ● PEP 489 , a new and improved mechanism for loading extension modules ● PEP 492 , coroutines with async and await syntax
  • 8. PEP 448 - additional unpacking generalizations >>> print(*[1], *[2], 3) 1 2 3 >>> dict(**{'x': 1}, y=2, **{'z': 3}) {'x': 1, 'y': 2, 'z': 3} >>> *range(4), 4 (0, 1, 2, 3, 4) >>> [*range(4), 4] [0, 1, 2, 3, 4] >>> {*range(4), 4} {0, 1, 2, 3, 4} >>> {'x': 1, **{'y': 2}} {'x': 1, 'y': 2} >>> {'x': 1, **{'x': 2}} {'x': 2} >>> {**{'x': 2}, 'x': 1} {'x': 1}
  • 9. PEP 484 - the typing module, a new standard for type annotations def greeting(name: str) -> str: return 'Hello ' + name from typing import * T = TypeVar('T') def filter(function: Optional[Callable[[T], Any]], iterable: Iterable[T]) -> Iterator[T]: ... Было Стало
  • 10. PEP 492 - coroutines with async and await syntax async def read_data(db): pass async def read_data(db): data = await db.fetch('SELECT ...') Новые ключевые слова: async и await
  • 11. 11 sapronov.alexander92@gmail.com @sapronovalex92 pynsk.nsk@gmail.com vk.com/pynsk facebook.com/PyNskCom @py_nsk PyNSK контакты: Мои контакты: ru.linkedin.com/in/alexsapronov Питоны кончились… Вопросы?