Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Wingardium Leviosa
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Serge Matveenko
April 25, 2014
Programming
0
160
Wingardium Leviosa
Python declarative magic basics
Serge Matveenko
April 25, 2014
Tweet
Share
More Decks by Serge Matveenko
See All by Serge Matveenko
Using NSQ in Python
lig
0
130
Build a container on Gitlab CI quest — Game Walkthrough
lig
0
200
Mnj — The MongoDB library which feels good
lig
0
170
Writing Dockerfile for a Python project the right way
lig
0
360
Pyventory for Ansible
lig
0
200
What time is it now?
lig
1
340
100% Test Covɘrage
lig
2
180
What in fact is this Python?
lig
2
200
Mnj — the MongoDB library which does it right
lig
1
280
Other Decks in Programming
See All in Programming
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
500
PJのドキュメントを全部Git管理にしたら、一番喜んだのはAIだった
nanaism
0
250
AIコーディングの理想と現実 2026 | AI Coding: Expectations vs. Reality 2026
tomohisa
0
1.2k
コーディングルールの鮮度を保ちたい / keep-fresh-go-internal-conventions
handlename
0
190
AI時代のシステム設計:ドメインモデルで変更しやすさを守る設計戦略
masuda220
PRO
5
850
Go Conference mini in Sendai 2026 : Goに新機能を提案し実装されるまでのフロー徹底解説
yamatoya
0
560
守る「だけ」の優しいEMを抜けて、 事業とチームを両方見る視点を身につけた話
maroon8021
3
740
RubyとGoでゼロから作る証券システム: 高信頼性が求められるシステムのコードの外側にある設計と運用のリアル
free_world21
0
260
AI主導でFastAPIのWebサービスを作るときに 人間が構造化すべき境界線
okajun35
0
700
20260228_JAWS_Beginner_Kansai
takuyay0ne
5
480
手戻りゼロ? Spec Driven Developmentとは@KAG AI week
tmhirai
1
190
ポーリング処理廃止によるイベント駆動アーキテクチャへの移行
seitarof
3
970
Featured
See All Featured
GitHub's CSS Performance
jonrohan
1032
470k
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.2k
Measuring & Analyzing Core Web Vitals
bluesmoon
9
780
What's in a price? How to price your products and services
michaelherold
247
13k
Abbi's Birthday
coloredviolet
2
5.3k
Making Projects Easy
brettharned
120
6.6k
Information Architects: The Missing Link in Design Systems
soysaucechin
0
820
Tell your own story through comics
letsgokoyo
1
840
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.3k
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
130
Money Talks: Using Revenue to Get Sh*t Done
nikkihalliwell
0
180
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.3k
Transcript
«Вингардиум левиоса» Основы декларативной магии Сергей Матвеенко
«Harry Potter and the Philosopher's Stone»
http://xkcd.com/353/
➢ Описания: существительные и прилагательные, а не глаголы ➢ Независимость
от реализации ➢ Валидация без компиляции ➢ Не нужно уметь программировать ➢ GUI для редактирования ➢ Потому что это модно :) Декларативное программирование
➢ Декораторы ➢ Метаклассы ◦ Атрибуты классов ◦ Аргументы классов
◦ Аннотации аргументов методов ➢ Import hooks ◦ Модификация AST ◦ Генерация кода ➢ Внешние описания ◦ YAML Декларативность в Python
Декораторы @this_is_decorator(safe_mode=True) def method(arg1, arg2): # we will have just
a few lines here return arg1 + arg2 @abstractclass class ObjectBase: def foo(self): return NotImplemented
Метаклассы: атрибуты классов class MyClass(ObjectBase): sequence = True sorted =
False seq = MyClass() seq.extend([3, 2, 5]) print(seq) > [3, 2, 5]
Метаклассы: атрибуты классов class ObjectMeta(type): def __new__(cls, name, bases, attrs):
type_new = type.__new__(cls, name, bases, attrs) if attrs.get('sequence', False): # add sequence realization if attrs.get('sorted', False): # add sorted realization return type_new class ObjectBase(metaclass=ObjectMeta): pass class MyClass(ObjectBase): sequence = True sorted = False
Метаклассы: аргументы классов class SequenceMeta(type): def __new__(cls, name, bases, attrs,
sorted=False): type_new = type.__new__(cls, name, bases, attrs) if sorted: # add sorted realization return type_new class SortedSequence(metaclass=SequenceMeta, sorted=True): pass seq = SortedSequence()
Метаклассы: аннотации import inspect class StrictMeta(type): def __new__(cls, name, bases,
args): type_new = type.__new__(cls, name, bases, args) for attr_name in dir(type_new): method = getattr(type_new.attr_name) if callable(method): parameters = inspect.signature(method).parameters.values() # construct decorated method setattr(new_type, attr_name, method) return new_type class TextNumber(metaclass=StrictMeta): value = "0" def __add__(self, value: r'[\d\.]+'): # add implementation return self.value
Import hooks: модификация AST # smart_sql.py class MyImporter: def load_module(self,
name): # modify AST return module sys.path_hooks.insert(0, MyImporter) # prog.py import smart_sql query = ( id, Point(x, y) for id, x, y in "sql_table_name" if len([(x0, y0), (x, y)]) < 3)
Import hooks: генерация кода # smart_sql.py class MyImporter: def find_module(self,
fullname, path=None): # find path to DSL source file self.path = path return self def load_module(self, name): # generate and compile python module from DSL return module sys.meta_path.insert(0, MyImporter) # prog.py import smart_sql from dsl_queries import query result = query.find(radius)
YAML # pytest-yamlwsgi test_index: - path: / assert_status: 200 assert_contains:
Hello - path: / assert_contains: Hello - path: / assert_status: 200
Django ORM from django.db import models class Musician(models.Model): first_name =
models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField()
Django class-based generic views class PublisherDetail(DetailView): context_object_name = 'publisher' queryset
= Publisher.objects.all() class BookList(ListView): queryset = Book.objects.order_by('-publication_date') context_object_name = 'book_list' class AcmeBookList(ListView): context_object_name = 'book_list' queryset = Book.objects.filter(publisher__name='Acme') template_name = 'books/acme_list.html'
Function annotations # http://code.activestate.com/recipes/578528/ @typecheck def happy1(a:int, b:list, c:tuple=(1,2,3)) ->
float: return 3.14 @typecheck def happy_wo_annotation(a:int, b, c:tuple=(1,2,3)) -> float: return 3.14 @typecheck def unhappy1(a:int, b:str) -> float: return 314 # This can never succeed in return type
Вопросы? github.com/lig ptsecurity.com