SlideShare a Scribd company logo
1 of 32
Download to read offline
Python
( h y )
a.zhlobich@gmail.com
anjensan
Minsk python meetup 2015-02
( недостатки python )
● Плохая многопоточность – GIL
● Медленный
● Явное указание self
● Куцие lambda выражения
● Слабые замыкания
● Отсутствие private
● Сложный рефакторинг
● Болезненный переход на 3
● Нет перегрузки методов
● Неоднородности ООП модели
● …
● Придумайте сами ...
( фатальный недостаток )
>>> from __future__ import braces
SyntaxError: not a chance
In a nutshell, Hy is a Lisp dialect, but one
that converts its structure into Python...
literally a conversion into Python’s abstract
syntax tree!
Or to put it in more crude terms,
Hy is lisp-stick on a Python!
( копипаста N
1 )
( копипаста N
2 )
● A Lisp that feels very Pythonic.
● For Lispers, a great way to use Lisp’s crazy
powers but in the wide world of Python’s
libraries (why yes, you now can write a Django
application in Lisp!)
● For Pythonistas, a great way to start exploring
Lisp, from the comfort of Python!
● For everyone: a pleasant language that has a
lot of neat ideas!
( на самом деле )
we do what we must,
because we can
just for fun
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Question
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
sc = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice."})
else:
sc.votes += 1
sc.save()
return HttpResponseRedirect(reverse('results', args=(p.id,)))
( код Py )
() - 9, [] - 1
(import [django.shortcuts [get-object-or-404 render]]
[django.http [HttpResponseRedirect HttpResponse]]
[django.core.urlresolvers [import reverse]]
[polls.models [Choice Question]])
(defn vote [request question-id]
(setv p (get-object-or-404 Question :pk question-id))
(try
(setv sc (p.choice-set.get :pk (. request.POST ["choice"])))
(except [KeyError Choice.DoesNotExist]
(render request "polls/detail.html"
{"question" p
"error_message" "You didn't select a choice."}))
(else
(+= sc.votes 1)
(sc.save)
(HttpResponseRedirect (reverse "results" :args [p.id])))))
( код Hy )
() - 15, [] - 12
( суть Hy )
Hy reader
Hy compiler
Hy AST
Python compiler
Python AST
CPython VM
Python bytecode
Hy stdlib
( py abstract syntax tree )
from ast import *
Module([
FunctionDef(
'my_fun',
arguments(args=[
Name('x', Param()),
Name('y', Param())]),
[Return(
BinOp(
Name('x', Load()),
Add(),
BinOp(
Num(2),
Mult(),
Name('y', Load()))))],
[])])
def my_fun(x, y):
return x + 2 * y
AST (py) Code
( hy abstract syntax tree )
from hy import *
HyExpression([
HySymbol('defn'),
HySymbol('my-fun'),
HyList([
HySymbol('x'),
HySymbol('y')]),
HyExpression([
HySymbol('+'),
HySymbol('x'),
HyExpression([
HySymbol('*'),
HyInteger(2),
HySymbol('y'),
])])])
Code
(defn my-fun [x y]
(+ x (* 2 y)))
AST (py)
( hy.models )
class HyObject(object):
def replace(self, other):
assert isinstance(other, HyObject)
for a in ["start_line", "end_line",
"start_column", "end_column"]:
if not hasattr(self, a) and hasattr(other, a):
setattr(self, a, getattr(other, a))
class HyString(HyObject, str):
pass
class HySymbol(HyString):
pass
class HyInteger(HyObject, int):
pass
# ...
# HyList, HyExpression, HyDict
# HyFloat, HyComplex, HyKeyword, HyCons
( большая разница )
'(defn my-fun [x y]
(+ x (* 2 y)))
(defn my-fun [x y]
(+ x (* 2 y)))
CodeAST (hy)
( vs )
123.4
None
"some string"
[1, 2, 3]
{"a": 1, "b": 2}
(1, 2, "z")
123.4
nil or
null or
None
"some string"
[1 2 3]
{"a" 1 "b" 2}
(, 1 2 "z")
Py Hy
( основа )
( verb n1
n2
… ns
) → r
Verb:
● Специальная форма
● Функция
● Метод объекта
● Макрос
. , != % %= & &= * ** **= *= + += - | / ~
/= < << <<= <= = > >= >> >>= ^ ^= -= |=
and apply assert assoc break catch
continue def defclass defmacro defreader
del dict-comp dispatch-reader-macro do
eval eval-and-compile eval-when-compile
except fn for* genexpr get global if
import in is is-not list-comp not not-in
or quasiquote quote raise require set-comp
setv slice try unquote unquote-splicing
while with* with-decorator
yield yield-from
( специальные формы )
( vs )
foo(x, y)
True or False
1 + 2
x = 123
"abbc".count("b")
vd[123]
(foo x y)
(or true false)
(+ 1 2)
(setv x 123)
(.count "abbc" "b")
(get vd 123)
Py Hy
( идентефикаторы )
hy_d1ahgkh6g
with_underscores
UPPER_CASE
_CamelCase
__magic__
is_pred
юникод
with-underscores
*upper-case*
-CamelCase
--magic--
pred?
Py Hy
( пример N
1 )
(defn my-sum [lst]
(setv x 0)
(for [e lst]
(print ">" e)
(+= x e))
x)
(print ":" (my-sum [1 2 3]))
;; > 1
;; > 2
;; > 3
;; : 6
( пример N
2 )
(import os)
(def hidden-files [])
(def all-files (os.listdir "."))
(for [f all-files]
(when (f.startswith ".")
(hidden-files.append f)))
(print
"hidden files:"
(.join ", " hidden-files))
(defclass Entry [models.Model]
[[headline (models.CharField :max-length 255)]
[body-text (models.TextField)]
[pub-date (models.DateField)]
[--str--
(fn [self] (+ "Entry:" self.headline))]])
(-> Entry.objects
(.filter :headline--startswith "What")
(.exclude :pub-date--gte (datetime.date.today))
(.order "headline")
(slice nil 10))
(.save
(Entry :headline "Text"
:body-text "Some text here"))
( пример N
3 )
( киллер-фича )
Метаклассы
Метапрограммирование
вид программирования, связанный с созданием
программ, которые порождают другие программы
как результат своей работы, либо программ,
которые меняют себя во время выполнения
( макросы )
Hy compiler
Python compiler
parser
lexer
macroexpand
S-exprs
ф-ии + спец.формы
+ макросы
S-exprs
ф-ии + спец. формы
run code
at compile time
( простейший )
(defmacro unless [expr &rest body]
`(if (not ~expr)
(do ~@body)))
(print ">>"
(unless (> 1 2)
(+= x 1)
(+= y 2)))
(print ">>"
(if (not (> 1 2))
(do
(+= x 1)
(+= y 2))))
( еще один... )
(import [collections [namedtuple]])
(defmacro deftuple [tname &rest columns]
`(def ~tname
(namedtuple
~(name tname)
~(list (map name columns)))))
;; ...
(deftuple Point x y)
(def a (Point 1 2))
(print a.x (get a 0))
( макрос "->" )
(defmacro -> [head &rest rest]
(setv ret head)
(for [node rest]
(if (not (isinstance node HyExpression))
(setv node `(~node)))
(.insert node 1 ret)
(setv ret node))
ret)
(defmacro my-> [head &rest rest]
(if rest
`(my->
(~(car (car rest))
~head
~@(cdr (car rest)))
~@(cdr rest))
head))
( reader macro )
(defreader a [vec]
`(numpy.array ~vec))
(print (+ #a [1 2 3 4 5]
#a (* [1] 5) ))
(defreader r [expr]
`(re.compile ~expr))
(print (.match
#r".*"
"some string"))
( let it be )
(defmacro let [vars &rest body]
`((fn []
~@(list-comp
`(setv ~k ~v)
[[k v] vars])
~@body)))
(let [[x 1]
[y 2]]
(let [[y 10]]
(+= y x) ;; ok
(assert (= 11 y))
;; (+= x 1) - fail!
)
(assert 3 (+ x y)))
• Hy -- это Python на S-exprs
• Есть плюсы, есть минусы
• Непривычный синтаксис
• Местами многословный
• Ма-акрос!
• Гибкость!
• Доступ к Python runtime
• Ведь Hy... всего лишь Python
( итого )
( спасибо )

More Related Content

Viewers also liked

Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedPython Meetup
 
Обзор способов написания конкурентных программ в питоне
Обзор способов написания конкурентных программ в питоне Обзор способов написания конкурентных программ в питоне
Обзор способов написания конкурентных программ в питоне Python Meetup
 
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingПро асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingPython Meetup
 
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...Python Meetup
 
Redis. Как мы боролись со сложностью
Redis. Как мы боролись со сложностьюRedis. Как мы боролись со сложностью
Redis. Как мы боролись со сложностьюPython Meetup
 
Python&Printer / Андрей Пучко / penta.by
Python&Printer / Андрей Пучко / penta.byPython&Printer / Андрей Пучко / penta.by
Python&Printer / Андрей Пучко / penta.byPython Meetup
 
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...Python Meetup
 
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотек
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотекSWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотек
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотекPython Meetup
 
Язык программирования GO
Язык программирования GOЯзык программирования GO
Язык программирования GOPython Meetup
 
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014Python Meetup
 
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]Python Meetup
 

Viewers also liked (11)

Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Обзор способов написания конкурентных программ в питоне
Обзор способов написания конкурентных программ в питоне Обзор способов написания конкурентных программ в питоне
Обзор способов написания конкурентных программ в питоне
 
Про асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer WargamingПро асинхронность / Максим Щепелин / Web Developer Wargaming
Про асинхронность / Максим Щепелин / Web Developer Wargaming
 
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...
OpenSource CMS и ERP система в одном флаконе / Олег Курьян / технический дире...
 
Redis. Как мы боролись со сложностью
Redis. Как мы боролись со сложностьюRedis. Как мы боролись со сложностью
Redis. Как мы боролись со сложностью
 
Python&Printer / Андрей Пучко / penta.by
Python&Printer / Андрей Пучко / penta.byPython&Printer / Андрей Пучко / penta.by
Python&Printer / Андрей Пучко / penta.by
 
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...
Как скачать статистику игроков World of Tanks / Павел Пересторонин [Python Me...
 
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотек
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотекSWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотек
SWIG — cоздание мультиязыковых интерфейсов для C/C++ библиотек
 
Язык программирования GO
Язык программирования GOЯзык программирования GO
Язык программирования GO
 
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
S.O.L.I.D. - Павел Кохан, Python Meetup 26.09.2014
 
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]
 

More from Python Meetup

Python для анализа данных
Python для анализа данныхPython для анализа данных
Python для анализа данныхPython Meetup
 
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...Python Meetup
 
Использование gevent для эмуляции высокой нагрузки
Использование gevent для эмуляции высокой нагрузкиИспользование gevent для эмуляции высокой нагрузки
Использование gevent для эмуляции высокой нагрузкиPython Meetup
 
Введение в GIL и новый GIL
Введение в GIL и новый GILВведение в GIL и новый GIL
Введение в GIL и новый GILPython Meetup
 
Недостатки Python
Недостатки PythonНедостатки Python
Недостатки PythonPython Meetup
 
Социальный игровой сервер на Python: от первого коммита до продакшена
Социальный игровой сервер на Python: от первого коммита до продакшенаСоциальный игровой сервер на Python: от первого коммита до продакшена
Социальный игровой сервер на Python: от первого коммита до продакшенаPython Meetup
 
Портируем на Python 3
Портируем на Python 3Портируем на Python 3
Портируем на Python 3Python Meetup
 
Garbage collector and a bit of memory management
Garbage collector and a bit of memory managementGarbage collector and a bit of memory management
Garbage collector and a bit of memory managementPython Meetup
 
Неочевидное поведение некоторых конструкций
Неочевидное поведение некоторых конструкцийНеочевидное поведение некоторых конструкций
Неочевидное поведение некоторых конструкцийPython Meetup
 
Pyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPython Meetup
 
Dictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtDictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtPython Meetup
 

More from Python Meetup (11)

Python для анализа данных
Python для анализа данныхPython для анализа данных
Python для анализа данных
 
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...
Асинхронное распределенное выполнение задач. Stdlib, Celery, RQ и собственные...
 
Использование gevent для эмуляции высокой нагрузки
Использование gevent для эмуляции высокой нагрузкиИспользование gevent для эмуляции высокой нагрузки
Использование gevent для эмуляции высокой нагрузки
 
Введение в GIL и новый GIL
Введение в GIL и новый GILВведение в GIL и новый GIL
Введение в GIL и новый GIL
 
Недостатки Python
Недостатки PythonНедостатки Python
Недостатки Python
 
Социальный игровой сервер на Python: от первого коммита до продакшена
Социальный игровой сервер на Python: от первого коммита до продакшенаСоциальный игровой сервер на Python: от первого коммита до продакшена
Социальный игровой сервер на Python: от первого коммита до продакшена
 
Портируем на Python 3
Портируем на Python 3Портируем на Python 3
Портируем на Python 3
 
Garbage collector and a bit of memory management
Garbage collector and a bit of memory managementGarbage collector and a bit of memory management
Garbage collector and a bit of memory management
 
Неочевидное поведение некоторых конструкций
Неочевидное поведение некоторых конструкцийНеочевидное поведение некоторых конструкций
Неочевидное поведение некоторых конструкций
 
Pyton – пробуем функциональный стиль
Pyton – пробуем функциональный стильPyton – пробуем функциональный стиль
Pyton – пробуем функциональный стиль
 
Dictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txtDictionary в Python. По мотивам Objects/dictnotes.txt
Dictionary в Python. По мотивам Objects/dictnotes.txt
 

Recently uploaded

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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 ApplicationsAlberto González Trastoy
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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.jsAndolasoft Inc
 
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.pdfWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
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.docxComplianceQuest1
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
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 ...harshavardhanraghave
 
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 PrecisionSolGuruz
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
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
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
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 ...
 
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
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Знакомство с Hy / Андрей Жлобич / Wargaming [Python Meetup 27.02.15]

  • 1. Python ( h y ) a.zhlobich@gmail.com anjensan Minsk python meetup 2015-02
  • 2. ( недостатки python ) ● Плохая многопоточность – GIL ● Медленный ● Явное указание self ● Куцие lambda выражения ● Слабые замыкания ● Отсутствие private ● Сложный рефакторинг ● Болезненный переход на 3 ● Нет перегрузки методов ● Неоднородности ООП модели ● … ● Придумайте сами ...
  • 3. ( фатальный недостаток ) >>> from __future__ import braces SyntaxError: not a chance
  • 4.
  • 5. In a nutshell, Hy is a Lisp dialect, but one that converts its structure into Python... literally a conversion into Python’s abstract syntax tree! Or to put it in more crude terms, Hy is lisp-stick on a Python! ( копипаста N 1 )
  • 6. ( копипаста N 2 ) ● A Lisp that feels very Pythonic. ● For Lispers, a great way to use Lisp’s crazy powers but in the wide world of Python’s libraries (why yes, you now can write a Django application in Lisp!) ● For Pythonistas, a great way to start exploring Lisp, from the comfort of Python! ● For everyone: a pleasant language that has a lot of neat ideas!
  • 7. ( на самом деле ) we do what we must, because we can just for fun
  • 8. from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from polls.models import Choice, Question def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: sc = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice."}) else: sc.votes += 1 sc.save() return HttpResponseRedirect(reverse('results', args=(p.id,))) ( код Py ) () - 9, [] - 1
  • 9. (import [django.shortcuts [get-object-or-404 render]] [django.http [HttpResponseRedirect HttpResponse]] [django.core.urlresolvers [import reverse]] [polls.models [Choice Question]]) (defn vote [request question-id] (setv p (get-object-or-404 Question :pk question-id)) (try (setv sc (p.choice-set.get :pk (. request.POST ["choice"]))) (except [KeyError Choice.DoesNotExist] (render request "polls/detail.html" {"question" p "error_message" "You didn't select a choice."})) (else (+= sc.votes 1) (sc.save) (HttpResponseRedirect (reverse "results" :args [p.id]))))) ( код Hy ) () - 15, [] - 12
  • 10. ( суть Hy ) Hy reader Hy compiler Hy AST Python compiler Python AST CPython VM Python bytecode Hy stdlib
  • 11. ( py abstract syntax tree ) from ast import * Module([ FunctionDef( 'my_fun', arguments(args=[ Name('x', Param()), Name('y', Param())]), [Return( BinOp( Name('x', Load()), Add(), BinOp( Num(2), Mult(), Name('y', Load()))))], [])]) def my_fun(x, y): return x + 2 * y AST (py) Code
  • 12. ( hy abstract syntax tree ) from hy import * HyExpression([ HySymbol('defn'), HySymbol('my-fun'), HyList([ HySymbol('x'), HySymbol('y')]), HyExpression([ HySymbol('+'), HySymbol('x'), HyExpression([ HySymbol('*'), HyInteger(2), HySymbol('y'), ])])]) Code (defn my-fun [x y] (+ x (* 2 y))) AST (py)
  • 13. ( hy.models ) class HyObject(object): def replace(self, other): assert isinstance(other, HyObject) for a in ["start_line", "end_line", "start_column", "end_column"]: if not hasattr(self, a) and hasattr(other, a): setattr(self, a, getattr(other, a)) class HyString(HyObject, str): pass class HySymbol(HyString): pass class HyInteger(HyObject, int): pass # ... # HyList, HyExpression, HyDict # HyFloat, HyComplex, HyKeyword, HyCons
  • 14. ( большая разница ) '(defn my-fun [x y] (+ x (* 2 y))) (defn my-fun [x y] (+ x (* 2 y))) CodeAST (hy)
  • 15. ( vs ) 123.4 None "some string" [1, 2, 3] {"a": 1, "b": 2} (1, 2, "z") 123.4 nil or null or None "some string" [1 2 3] {"a" 1 "b" 2} (, 1 2 "z") Py Hy
  • 16. ( основа ) ( verb n1 n2 … ns ) → r Verb: ● Специальная форма ● Функция ● Метод объекта ● Макрос
  • 17. . , != % %= & &= * ** **= *= + += - | / ~ /= < << <<= <= = > >= >> >>= ^ ^= -= |= and apply assert assoc break catch continue def defclass defmacro defreader del dict-comp dispatch-reader-macro do eval eval-and-compile eval-when-compile except fn for* genexpr get global if import in is is-not list-comp not not-in or quasiquote quote raise require set-comp setv slice try unquote unquote-splicing while with* with-decorator yield yield-from ( специальные формы )
  • 18. ( vs ) foo(x, y) True or False 1 + 2 x = 123 "abbc".count("b") vd[123] (foo x y) (or true false) (+ 1 2) (setv x 123) (.count "abbc" "b") (get vd 123) Py Hy
  • 20. ( пример N 1 ) (defn my-sum [lst] (setv x 0) (for [e lst] (print ">" e) (+= x e)) x) (print ":" (my-sum [1 2 3])) ;; > 1 ;; > 2 ;; > 3 ;; : 6
  • 21. ( пример N 2 ) (import os) (def hidden-files []) (def all-files (os.listdir ".")) (for [f all-files] (when (f.startswith ".") (hidden-files.append f))) (print "hidden files:" (.join ", " hidden-files))
  • 22. (defclass Entry [models.Model] [[headline (models.CharField :max-length 255)] [body-text (models.TextField)] [pub-date (models.DateField)] [--str-- (fn [self] (+ "Entry:" self.headline))]]) (-> Entry.objects (.filter :headline--startswith "What") (.exclude :pub-date--gte (datetime.date.today)) (.order "headline") (slice nil 10)) (.save (Entry :headline "Text" :body-text "Some text here")) ( пример N 3 )
  • 23.
  • 24. ( киллер-фича ) Метаклассы Метапрограммирование вид программирования, связанный с созданием программ, которые порождают другие программы как результат своей работы, либо программ, которые меняют себя во время выполнения
  • 25. ( макросы ) Hy compiler Python compiler parser lexer macroexpand S-exprs ф-ии + спец.формы + макросы S-exprs ф-ии + спец. формы run code at compile time
  • 26. ( простейший ) (defmacro unless [expr &rest body] `(if (not ~expr) (do ~@body))) (print ">>" (unless (> 1 2) (+= x 1) (+= y 2))) (print ">>" (if (not (> 1 2)) (do (+= x 1) (+= y 2))))
  • 27. ( еще один... ) (import [collections [namedtuple]]) (defmacro deftuple [tname &rest columns] `(def ~tname (namedtuple ~(name tname) ~(list (map name columns))))) ;; ... (deftuple Point x y) (def a (Point 1 2)) (print a.x (get a 0))
  • 28. ( макрос "->" ) (defmacro -> [head &rest rest] (setv ret head) (for [node rest] (if (not (isinstance node HyExpression)) (setv node `(~node))) (.insert node 1 ret) (setv ret node)) ret) (defmacro my-> [head &rest rest] (if rest `(my-> (~(car (car rest)) ~head ~@(cdr (car rest))) ~@(cdr rest)) head))
  • 29. ( reader macro ) (defreader a [vec] `(numpy.array ~vec)) (print (+ #a [1 2 3 4 5] #a (* [1] 5) )) (defreader r [expr] `(re.compile ~expr)) (print (.match #r".*" "some string"))
  • 30. ( let it be ) (defmacro let [vars &rest body] `((fn [] ~@(list-comp `(setv ~k ~v) [[k v] vars]) ~@body))) (let [[x 1] [y 2]] (let [[y 10]] (+= y x) ;; ok (assert (= 11 y)) ;; (+= x 1) - fail! ) (assert 3 (+ x y)))
  • 31. • Hy -- это Python на S-exprs • Есть плюсы, есть минусы • Непривычный синтаксис • Местами многословный • Ма-акрос! • Гибкость! • Доступ к Python runtime • Ведь Hy... всего лишь Python ( итого )