O documento discute metaprogramação em Python, incluindo:
1) Metaprogramação permite que programas sejam capazes de modificar outros programas;
2) Em Python tudo é objeto e pode ser modificado dinamicamente através de metaprogramação;
3) Técnicas como method missing, metaclasses e built-in types permitem customizar a linguagem.
20. Lazy load
class SemanticEntity(object):
def __init__(self, uri):
self.uri = uri
self.attrs = None
def __getattr__(self, attr):
self.__lazy_load()
val = self.attrs.get(attr)
if self.__is_entity(val):
return self.__class__(val)
return val
def __lazy_load(self):
if self.attrs is None:
self.__load()
22. Conquistar uma namorada
class Pessoa(object):
def coracao(self, v):
if v == 3:
return "Zilah"
__lt__ = coracao
tiago = Pessoa()
print tiago <3
23. Metaprogramação em python
● Tudo é objeto, tudo é atribuível
● Method missing
● Metaclasses
● Builtins types
24. O que é?
Classe:
→ Fábica de instâncias
Metaclasse:
→ Fábrica de classes
25. Metaclasse... chata
class MetaClasseChata(type):
def __new__(cls, name, bases, dct):
print "Alocando memoria para %s" % name
return type.__new__(cls, name, bases, dct)
def __init__(cls, name, bases, dct):
print "Criando classe %s" % name
super(MetaClasseChata, cls).__init__(name,bases,dct)
def metodo_da_classe(cls):
print "Metodo da classe"
26. Metaclasse... chata
class ClasseChata(object):
__metaclass__ = MetaClasseChata
print ClasseChata.metodo_da_classe()
print type(ClasseChata)
----------------------------------------------------
Alocando memoria para ClasseChata
Criando classe ClasseChata
Metodo da classe
<class '__main__.MetaClasseChata'>
27. Um exemplo legal
Selfless python
Por João Sebastião de Oliveira Bueno
http://metapython.blogspot.com
28. Mas antes: Descriptors
from random import random
class NumeroAleatorioDescriptor(object):
def __get__(self, instance, classe):
return int(random()*100)
class Roleta(object):
valor = NumeroAleatorioDescriptor()
print Roleta().valor
29. Selfless python
class SelflessDescriptor(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, class_):
new_globals = self.func.func_globals.copy()
new_globals["self"] = instance
new_func = FunctionType(self.func.func_code,
new_globals, self.func.func_name,
self.func.func_defaults,
self.func.func_closure)
return new_func
class Selfless(type):
def __new__(cls, name, bases, dict_):
for key, val in dict_.items():
if isinstance(val, FunctionType):
dict_[key] = SelflessDescriptor(val)
return type(name, bases, dict_)
30. Selfless python
__metaclass__ = Selfless
class A:
def __init__(a, b):
self.a = a
self.b = b
31. Metaprogramação em python
● Tudo é objeto, tudo é atribuível
● Method missing
● Metaclasses
● Builtins types
32. Fuuuuuuuu
from datetime import datetime
datetime.now = lambda: None
TypeError: can't set attributes of built-in/extension
type 'datetime.datetime'
set.get = lambda: None
TypeError: can't set attributes of built-in/extension type 'set'
list.index = lambda i: None
TypeError: can't set attributes of built-in/extension type 'list'
str.split = lambda: None
TypeError: can't set attributes of built-in/extension type 'str'
33. Datetime: Jeitinho brasileiro
import datetime as dt_module
from datetime import datetime
class TestArtist(TestCase):
def test_should_find_news_by_date(self):
today = datetime.today()
dt_module.datetime = DateTimeFake(today)
def get_by_date_fake(obj, date):
self.used_date = date
return []
NewsRepository.get_by_date = get_by_date_fake
Artist().news()
assert self.used_date == today
34. O jeito é uma herancinha
com você
class BetterDict(dict):
def __getattr__(self, attr):
return self.__getitem__(attr)
def __setattr__(self, attr, val):
self.__setitem__(attr, val)
x = BetterDict({'a': 'A'})
x['b'] = 'B'
x.c = 'C'
print x.a, x.b, x.c → A B C
print x['a'], x['b'], x['c'] → A B C
35. O jeito é uma herancinha
com você
class BetterList(list):
def subtraction(self, other):
for i in other:
if i in self:
self.remove(i)
return self
__isub__ = subtraction
x = BetterList([1,2,3,4])
x -= [2, 4]
print x → [1, 3]
36. Outras coisas legais...
… mas que não são metaprogramação
● Decorators
● With Statement
● Multiprocessing