├── .gitignore ├── metapython.odp ├── LICENSE ├── meta_getattr.py ├── metapython.txt ├── curry_decorator.py ├── pyschemificator.py ├── static.py ├── tailrecursion.py ├── polymorph.py ├── README.md ├── aspect.py ├── lazy_decorator.py ├── LGPL-3.0 └── privateattr.py /.gitignore: -------------------------------------------------------------------------------- 1 | .hg 2 | *pyc 3 | __pycache__/* 4 | -------------------------------------------------------------------------------- /metapython.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jsbueno/metapython/HEAD/metapython.odp -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Author: João S. O. Bueno 2 | Copyright 2006-2016 - João S. O. Bueno 3 | All files on this repository are subject to the LGPL v 3.0 or later, 4 | as stated on the LGPL file. 5 | Exception the 'aspect.py' file - that program alone is licensed under 6 | the MIT license as embedded on the file itself. 7 | -------------------------------------------------------------------------------- /meta_getattr.py: -------------------------------------------------------------------------------- 1 | class Meta(type): 2 | def __getattribute__(self, attr): 3 | if attr.startswith("__"): 4 | return type.__getattribute__(self, attr) 5 | print attr, dir(self.__dict__[attr]) 6 | v = type.__getattribute__(self, attr) 7 | print attr, dir(v) 8 | return v 9 | 10 | 11 | __metaclass__ = Meta 12 | 13 | class A: 14 | def a(self): 15 | pass 16 | 17 | -------------------------------------------------------------------------------- /metapython.txt: -------------------------------------------------------------------------------- 1 | MetaPython: quando trocamos os encanamentos! 2 | 3 | Python é versátil o suficiente para, sem quebrar as regras da linguagem, podermos implementar polimorfismo, tail recursion, lazy execution, checagem de tipos, atributos privados, mudar o "jeito" da linguagem para que lembre LISP, ou Forth, ou ainda fazer tudo em uma única expressão de uma linha. Usando os vários recursos entre metaclasses, decorators, introspecção dos frames de execução, são mostrados exemplos de cada uma dessas coisas for fun & profit. -------------------------------------------------------------------------------- /curry_decorator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from functools import partial, wraps 3 | 4 | """Curry decorator for "currying" functions acording to lambda calculus. 5 | Check http://en.wikipedia.org/wiki/Lambda_calculus 6 | for more 7 | """ 8 | 9 | def curry(func): 10 | @wraps(func) 11 | def wrapper(*args, **kw): 12 | return partial(func, *args, **kw) 13 | return wrapper 14 | 15 | if __name__ == "__main__": 16 | @curry 17 | def somaquad(a, b): 18 | return a * a + b * b 19 | 20 | b = somaquad(3)(4) 21 | print b -------------------------------------------------------------------------------- /pyschemificator.py: -------------------------------------------------------------------------------- 1 | from inspect import stack 2 | 3 | def define(*y): 4 | parent_frame = stack()[-2][0] 5 | parent_frame.f_globals[y[0]] = y[1] if (len(y) < 3 ) else y[1:] 6 | 7 | d = define 8 | 9 | def cond(*l): 10 | for item in l: 11 | if hasattr(item, "__len__") and len(item) >= 2: 12 | if item[0]: 13 | return item[1:] 14 | else: 15 | return item 16 | return None 17 | 18 | c = cond 19 | 20 | def if_(*l): 21 | return cond((l[0], l[1]), l[2] if len(l) == 2 else None) 22 | 23 | def scheme(*l): 24 | if len(l): 25 | return l[0](*l[1:]) 26 | else: 27 | return None 28 | 29 | s = scheme 30 | 31 | s(define, "add", lambda *x: sum(x)) 32 | s(define, "mul", lambda x, y: x * y) 33 | s(define, "square", lambda x: s(mul, x, x)) 34 | s(define, "sum_of_squares", lambda x,y: s(add, s(square, x), s(square, y))) 35 | print s(sum_of_squares, 3, 4) 36 | -------------------------------------------------------------------------------- /static.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from functools import wraps 3 | 4 | 5 | class Staticator(object): 6 | def __init__(self, *args, **kw): 7 | self.types = args 8 | self.kw_types = kw 9 | 10 | def __call__(self, function): 11 | self.func_name = function.func_name 12 | @wraps(function) 13 | def new_function(*args, **kw): 14 | self.check_args(args, kw) 15 | return function(*args, **kw) 16 | return new_function 17 | 18 | def raise_type_error(self, arg, type_): 19 | raise TypeError( 20 | "Incorrect argument %s - should be of type %s in call to %s()" % 21 | (str(arg), str(type_), self.func_name)) 22 | 23 | def check_args(self, args, kw): 24 | for type_, arg in zip(self.types, args): 25 | if not isinstance(arg, type_): 26 | self.raise_type_error(arg, type_) 27 | for key in kw: 28 | try: 29 | if not isinstance(kw[key], self.kw_types[key]): 30 | self.raise_type_error(kw[key], type_) 31 | except KeyError: 32 | raise TypeError("%s() got an unexpected " 33 | "keyword argument '%s'" % 34 | (self.func_name, key)) 35 | 36 | if __name__ == "__main__": 37 | @Staticator(int, int) 38 | def sum(a, b): 39 | return a + b 40 | 41 | sum(2,3) 42 | sum(2.0, 3) -------------------------------------------------------------------------------- /tailrecursion.py: -------------------------------------------------------------------------------- 1 | from threading import currentThread 2 | 3 | class TailRecursiveCall(Exception): 4 | pass 5 | 6 | def tailrecursive(f): 7 | class Rec_f(object): 8 | def __init__(self): 9 | self.tr_d = {} 10 | 11 | def __call__(self, *args, **kw): 12 | self.args = args 13 | self.kw = kw 14 | thread = currentThread() 15 | if thread not in self.tr_d: 16 | self.tr_d[thread] = {} 17 | self.tr_d[thread]["depth"] = 0 18 | 19 | self.tr_d[thread]["depth"] += 1 20 | self.tr_d[thread]["args"] = args 21 | self.tr_d[thread]["kw"] = kw 22 | depth = self.tr_d[thread]["depth"] 23 | if depth > 1: 24 | raise TailRecursiveCall 25 | over = False 26 | while not over: 27 | over = True 28 | args = self.tr_d[thread]["args"] 29 | kw = self.tr_d[thread]["kw"] 30 | #print "meta depth: %d" % depth 31 | try: 32 | result = f (*args, **kw) 33 | except TailRecursiveCall: 34 | self.tr_d[thread]["depth"] -= 1 35 | over = False 36 | self.tr_d[thread]["depth"] -= 1 37 | return result 38 | 39 | return Rec_f() 40 | 41 | 42 | def fatorial (n): 43 | if n == 1: 44 | return 1 45 | return n * fatorial(n -1) 46 | 47 | 48 | @tailrecursive 49 | def tail_fatorial (n, a=1): 50 | if n == 1: 51 | return a * 1 52 | return tail_fatorial(n -1, n * a) 53 | 54 | 55 | if __name__ == "__main__": 56 | 57 | try: 58 | print "999! %d" % fatorial(999) 59 | print "2000! %d" % fatorial (2000) 60 | except RuntimeError, error: 61 | print "Fatorial normal quebrou: %s " % str(error) 62 | 63 | 64 | try: 65 | print "999! %d" % tail_fatorial(999) 66 | print "2000! %d" % tail_fatorial (3000) 67 | except RuntimeError, error: 68 | print "Fatorial tail tambem quebrou: %s" %str(error) 69 | -------------------------------------------------------------------------------- /polymorph.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from functools import wraps 3 | 4 | 5 | 6 | class Polymorphator(object): 7 | __metaclass__ = type 8 | polymorphators = {} 9 | def __init__(self): 10 | if not hasattr(self.__class__, "current_class"): 11 | self.__class__.current_polymorphator = para_polymorphator_factory() 12 | def __call__(self, *args, **kw): 13 | return self.__class__.current_polymorphator(*args, **kw) 14 | @classmethod 15 | def commit_class(cls, class_name): 16 | cls.polymorphators[class_name] = cls.current_polymorphator 17 | cls.current_polymorphator = para_polymorphator_factory() 18 | 19 | 20 | class MetaPolymorphator(type): 21 | def __new__(cls, name, bases, dict_): 22 | Polymorphator.commit_class(name) 23 | function_type = type(lambda:None) 24 | for key, value in dict_.items(): 25 | if isinstance(value, function_type) and hasattr(value, "polymorphed"): 26 | base_homonimous = {} 27 | # FIXME: not recursing bases (have to do so in proper reversed(MRO)) 28 | for base in reversed(bases): 29 | base_name = base.__name__ 30 | if base_name in Polymorphator.polymorphators: 31 | methods = Polymorphator.polymorphators[base_name].methods 32 | if key in methods: 33 | base_homonimous.update(methods[key]) 34 | Polymorphator.polymorphators[name].methods[key].update(base_homonimous) 35 | return type.__new__(cls, name, bases, dict_) 36 | 37 | 38 | __metaclass__ = MetaPolymorphator 39 | 40 | 41 | def para_polymorphator_factory(): 42 | class ParaPolymorphator(object): 43 | __metaclass__ = type 44 | methods = {} 45 | 46 | def __init__(self, *args, **kw): 47 | self.methods = {} 48 | self.signature = self.get_reg_signature(args, kw) 49 | 50 | def get_reg_signature(self, args, kw): 51 | return (tuple(args), tuple(sorted(kw.items()))) 52 | 53 | def get_run_signature(self, args, kw): 54 | argstuple = tuple((type(arg) for arg in args[1:])) 55 | kwtuple = tuple(sorted (((item[0], type(item[1])) for item in kw.items() )) ) 56 | return (argstuple, kwtuple) 57 | 58 | def __call__(self, method): 59 | name = method.func_name 60 | if not name in self.__class__.methods: 61 | self.__class__.methods[name] = {self.signature: method} 62 | else: 63 | self.__class__.methods[name][self.signature] = method 64 | @wraps(method) 65 | def new_function(*args, **kw): 66 | signature = self.get_run_signature(args, kw) 67 | try: 68 | return self.__class__.methods[name][signature](*args, **kw) 69 | except KeyError: 70 | raise TypeError("No method '%s' registered for signature %s" 71 | %(name, str(signature))) 72 | new_function.polymorphed = True 73 | return new_function 74 | return ParaPolymorphator 75 | 76 | polymorphator = Polymorphator() 77 | 78 | ##testclasses: 79 | 80 | class A: 81 | @polymorphator(int, int) 82 | def sum(self, a, b): 83 | print "A soma de %d e %d é: %d" % (a, b, a+b) 84 | 85 | @polymorphator(str, str) 86 | def sum(self, a, b): 87 | print "A concatenação de %s e %s é: %s" % (a, b, a + " - " + b) 88 | 89 | class B: 90 | @polymorphator(float, float) 91 | def sum(self, a, b): 92 | print "A soma de %f e %f é: %f" % (a, b, a+b) 93 | 94 | class C(A): 95 | @polymorphator(complex, complex) 96 | def sum(self, a, b): 97 | print "A soma dos complexos %s e %s é: %s" % (a, b, a+b) 98 | 99 | if __name__ == "__main__": 100 | a = A() 101 | a.sum(2,3) 102 | a.sum("maçã", "laranja") 103 | b = B() 104 | b.sum(2.5,3.1) 105 | try: 106 | b.sum(2,3) 107 | except TypeError, error: 108 | print "Properly raised Typerror: %s" %error 109 | c = C() 110 | c.sum(1 + 1j, -1j) 111 | c.sum(4, 8) 112 | try: 113 | c.sum(2.1,3.1) 114 | except TypeError, error: 115 | print "Properly raised Typerror: %s" %error 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MetaPython: quando trocamos os encanamentos! 2 | 3 | Python é versátil o suficiente para, sem quebrar as regras da linguagem, podermos implementar polimorfismo, tail recursion, lazy execution, checagem de tipos, atributos privados, mudar o "jeito" da linguagem para que lembre LISP, ou Forth, ou ainda fazer tudo em uma única expressão de uma linha. Usando os vários recursos entre metaclasses, decorators, introspecção dos frames de execução, são mostrados exemplos de cada uma dessas coisas for fun & profit. 4 | 5 | * Function Decorators 6 | 7 | Permitem processar um objeto função assim que ele é instanciado. 8 | 9 | O processo permite mudar atributos de uma função, 10 | 11 | 12 | permite fazer o ^wrap de uma função com código que 13 | muodifica seu comportamento. 14 | 15 | 16 | As vezes até entendemos o conceito, 17 | mas não sabemos onde usar 18 | 19 | Um exemplo simples, pode ser anotação de tipos. 20 | 21 | 22 | def sum(a, b): 23 | if not is instance(a, int) or not isinstance(b, int): 24 | raise TypeError 25 | 26 | 27 | < 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | this software and associated documentation files (the "Software"), to deal in 10 | the Software without restriction, including without limitation the rights to 11 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 12 | of the Software, and to permit persons to whom the Software is furnished to do 13 | so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included in all 16 | copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | 26 | ------------------------------------------------------------------------------ 27 | 28 | Exemplo didático de implementação de programação orientada 29 | a aspectos com Python. 30 | 31 | Sem otimizações que seriam prematuras 32 | Caso deseje um uso real programação orientada a aspectos com python, 33 | existem alguns projetos bem mantidos em repositórios apropriados 34 | na internet. È melhor usar um desses do que re-inventar a roda 35 | """ 36 | class Aspecter(type): 37 | """ 38 | Meta classe usada por classes que terão métodos orientados 39 | a aspecto (com os join-points e cross-cut points e etc. 40 | 41 | O objeto aspect_rules contém todas as regras de aspecto 42 | """ 43 | aspect_rules = [] 44 | wrapped_methods = [] 45 | def __new__(cls, name, bases, dict): 46 | """ 47 | Inicialização de classe que contém métodos orientados a aspectos. 48 | Basicamente anota todos os métodos da classe de forma que a cada 49 | chamada possa ser verificado se há uma regra correspondente 50 | aos mesmos: 51 | """ 52 | for key, value in dict.items(): 53 | if hasattr(value, "__call__") and key != "__metaclass__": 54 | dict[key] = Aspecter.wrap_method(value) 55 | return type.__new__(cls, name, bases, dict) 56 | 57 | @classmethod 58 | def register(cls, name_pattern="", in_objects=(), out_objects=(), 59 | pre_function=None, 60 | post_function=None): 61 | """ 62 | Método usado para registrar uma nova regra de aspecto. 63 | O registro pode ser feito dinamicamente em tempo de execução 64 | name_pattern: é uma expressão regular que casa com o nome dos 65 | métodos. em branco, casa com todos os métodos. 66 | 67 | Em particular, note que esse esquema simplificado não dá conta 68 | de chamar uma pre_function baseando-se em out_objects 69 | """ 70 | # Método to simples que poderia ser usado um append direto em 71 | # "aspect rules" 72 | rule = {"name_pattern": name_pattern, "in_objects": in_objects, 73 | "out_objects": out_objects, 74 | "pre": pre_function, "post": post_function} 75 | cls.aspect_rules.append(rule) 76 | 77 | @classmethod 78 | def wrap_method(cls, method): 79 | def call(*args, **kw): 80 | pre_functions = cls.matching_pre_functions(method, args, kw) 81 | for function in pre_functions: 82 | function(*args, **kw) 83 | results = method(*args, **kw) 84 | post_functions = cls.matching_post_functions(method, results) 85 | for function in post_functions: 86 | function(results, *args, **kw) 87 | return results 88 | return call 89 | 90 | @classmethod 91 | def matching_names(cls, method): 92 | return [rule for rule in cls.aspect_rules 93 | if re.match(rule["name_pattern"], method.func_name) 94 | or rule["name_pattern"] == "" 95 | ] 96 | 97 | @classmethod 98 | def matching_pre_functions(cls, method, args, kw): 99 | all_args = args + tuple(kw.values()) 100 | return [rule["pre"] for rule in cls.matching_names(method) 101 | if rule["pre"] and 102 | (rule["in_objects"] == () or 103 | any((type(arg) in rule["in_objects"] for arg in all_args))) 104 | ] 105 | @classmethod 106 | def matching_post_functions(cls, method, results): 107 | if type(results) != tuple: 108 | results = (results,) 109 | return [rule["post"] for rule in cls.matching_names(method) 110 | if rule["post"] and 111 | (rule["out_objects"] == () or 112 | any((type(result) in rule["out_objects"] for result in results))) 113 | ] 114 | 115 | if __name__ == "__main__": 116 | #testing 117 | class Address(object): 118 | def __repr__(self): 119 | return "Address..." 120 | 121 | 122 | class Person(object): 123 | __metaclass__ = Aspecter 124 | def updateAddress(self, address): 125 | pass 126 | def __str__(self): 127 | return "person object" 128 | 129 | def log_update(*args, **kw): 130 | print "Updating object %s" %str(args[0]) 131 | 132 | def log_address(*args, **kw): 133 | addresses = [arg for arg in (args + tuple(kw.values())) 134 | if type(arg) == Address] 135 | print addresses 136 | 137 | Aspecter.register(name_pattern="^update.*", pre_function=log_update) 138 | Aspecter.register(in_objects=(Address,), pre_function=log_address) 139 | 140 | p = Person() 141 | p.updateAddress(Address()) 142 | 143 | -------------------------------------------------------------------------------- /lazy_decorator.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Author: João S. O. Bueno 5 | # copyright (c): João S. O. Bueno 2009 6 | # License: LGPL V3.0 7 | 8 | # This module is free software; you can redistribute it and/or 9 | # modify it under the terms of the GNU Lesser General Public 10 | # License as published by the Free Software Foundation; either 11 | # version 3 of the License, or (at your option) any later version. 12 | # 13 | # This module is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | # Lesser General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Lesser General Public 19 | # License along with this module; if not, see . 20 | 21 | 22 | # KNOWN Bugs: 23 | # 1) Could not make it work for arithmetic operations with float or complex 24 | # when the lazy evaluated value is a number. (Maybe explicetly implement the 25 | # __r..__ methods? ) 26 | # 2) Some sequence type methods for non -sequence objects 27 | # are returning "not implemented" when they should raise a typeerror 28 | 29 | 30 | from functools import wraps 31 | def lazy(func): 32 | class Template(object): 33 | def __init__(self, *args, **kw): 34 | self.args = args 35 | self.kw = kw 36 | self.executed = False 37 | def _exec(self): 38 | if not self.executed: 39 | self.value = func(*self.args, **self.kw) 40 | self.executed = True 41 | return self.value 42 | 43 | def __setattr__(self, attr, value): 44 | if attr not in ("args", "kw", "executed", "value"): 45 | return setattr(self._exec(), attr, value) 46 | return object.__setattr__(self, attr, value) 47 | 48 | def __getattr__(self, attr): 49 | if attr not in ("args", "kw", "executed", "value"): 50 | return self._exec().__getattribute__(attr) 51 | return object.__getattr__(self, attr) 52 | 53 | def __unicode__(self): 54 | return unicode(self._exec()) 55 | 56 | # FIXME, DOUBT: should the closure's values be frozen at function call time? guess not! 57 | func_closure = func.func_closure 58 | 59 | # The core of it all: create a a suply of every possible way of using an 60 | # object, assuring the function call happens as the object is used 61 | 62 | #FIXME: Maybe remove the actual function call one further level, 63 | # creating a class at the evaluation moment 64 | # so that once the function is evaluated, only the pertinent 65 | # methods would exist for the class 66 | 67 | def meta_meta_method(method_name, error="TypeError"): 68 | def meta_method(self, *args,**kw): 69 | #FIXME: will get strange not implemented errors - example: 70 | # "NotImplemented: '__getitem__'" instead of: 71 | # "TypeError: 'int' object is unsubscriptable" 72 | # for the delayed function call returned values 73 | try: 74 | method = getattr(self._exec(), method_name) 75 | except AttributeError: 76 | if error == "NotImplemented": 77 | return NotImplemented 78 | else: 79 | raise TypeError, ("%s object can't do %s" % ( 80 | type(self._exec()), 81 | method_name.replace("__", "") 82 | )) 83 | return method(*args,**kw) 84 | #FIXME: maybe this hides the nature of these objects 85 | #and maybe this hiding should be avoided at all: 86 | meta_method.func_name = method_name 87 | return meta_method 88 | 89 | optional_methods = """__lt__ __eq__ __ne__ __gt__ __ge__ """.split() 90 | 91 | data_model_methods = """ 92 | __repr__ __str__ __cmp__ 93 | __hash__ __nonzero__ 94 | __delattr__ 95 | __call__ 96 | __len__ __getitem__ __setitem__ __delitem__ __reversed__ __contains__ 97 | __add__ __sub__ __mul__ __floordiv__ __mod__ __divmod__ __pow__ __div__ __truediv__ 98 | __lshift__ __rshift__ __and__ __xor__ __or__ 99 | __radd__ __rsub__ __rmul__ __rfloordiv__ __rmod__ __rdivmod__ 100 | __rpow__ __rdiv__ __rtruediv__ 101 | __rlshift__ __rrshift__ __rand__ __rxor__ __ror__ 102 | __iadd__ __isub__ __imul__ __ifloordiv__ __imod__ __ipow__ __idiv__ __itruediv__ 103 | __ilshift__ __irshift__ __iand__ __ixor__ __ior__ 104 | __neg__ __pos__ __abs__ __invert__ 105 | __complex__ __int__ __long__ __float__ 106 | __oct__ __hex__ 107 | __index__ __coerce__ 108 | """.split() 109 | optional_methods = """__lt__ __eq__ __ne__ __gt__ __ge__ __unicode__""".split() 110 | # FIXME: left out: __getslice__ __setslice__ __delslice__ 111 | 112 | data_model_dict = dict([(method_name, meta_meta_method(method_name)) 113 | for method_name in data_model_methods]) 114 | optional_dict = dict([(method_name, meta_meta_method(method_name, error="NotImplemented")) 115 | for method_name in data_model_methods]) 116 | 117 | data_model_dict.update(optional_dict) 118 | 119 | LazyFuncClass = type("Lazy_%s" %func.func_name, (Template,), data_model_dict) 120 | 121 | #functools.wraps -> for decorators: preserves some of the original function attributes 122 | @wraps(func) 123 | def _call_(*args,**kw): 124 | return LazyFuncClass (*args,**kw) 125 | 126 | return _call_ 127 | 128 | if __name__ == "__main__": 129 | @lazy 130 | def bla(x): 131 | print "bla in execution for %s" % x 132 | return x 133 | ob_a = bla(3) 134 | print "ob_a created - should be evaluated in the line bellow" 135 | print ob_a + 2 136 | 137 | """ 138 | @lazy 139 | def proc(): 140 | return proc() 141 | 142 | 143 | class Tracer(object): 144 | def __getattribute__(self, attr): 145 | print attr 146 | return object.__getattribute__(self, attr) 147 | 148 | from lazy_decorator import lazy 149 | 150 | @lazy 151 | def openfile(fn, mode="rt"): 152 | print "opening" , fn 153 | return open(fn, mode) 154 | 155 | arq = openfile("teste", "wb") 156 | 157 | class A(object): 158 | @lazy 159 | def add(self, a, b): 160 | print "adding: %s, %s" %(a,b) 161 | return a + b 162 | 163 | @lazy 164 | def bla(x): 165 | print "bla in execution for %s" % x 166 | return x 167 | """ -------------------------------------------------------------------------------- /LGPL-3.0: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /privateattr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Author: Pedro Werneck, João S. O. Bueno 3 | 4 | 5 | 6 | import inspect 7 | import sys 8 | import types 9 | 10 | 11 | # Exception to use 12 | class PrivateAttributeError(AttributeError): 13 | pass 14 | 15 | 16 | # Check if the caller is legit at all levels... can be improved 17 | def check_caller(obj, level): 18 | frame = sys._getframe(level) 19 | cls = type(obj) 20 | 21 | # first of all, the instance has to be in the frame 22 | values = frame.f_locals.values() 23 | if obj not in values: 24 | raise PrivateAttributeError("Instance not in frame!") 25 | 26 | for attr, func in cls.__dict__.items(): 27 | if not isinstance(func, types.FunctionType): 28 | continue 29 | code1 = func.func_code 30 | code2 = frame.f_code 31 | if code1 is code2: 32 | # we found the same code in a method, 33 | break 34 | # FIXME: have to find a way to check if it's an original 35 | # method and not added later 36 | 37 | else: 38 | # ops, ran out the loop... raise error 39 | raise PrivateAttributeError("caller not a method") 40 | 41 | 42 | # Base Private attribute descriptor... not sure if it'll work with 43 | # methods as is now 44 | class PrivateAttribute(object): 45 | def __init__(self, name): 46 | self.name = name 47 | 48 | def __get__(self, obj, cls=None): 49 | check_caller(obj, 2) 50 | try: 51 | value = obj.__privdict__[self.name] 52 | except KeyError: 53 | raise AttributeError("Private attribute '%s' not set"%self.name) 54 | return value 55 | 56 | def __set__(self, obj, value): 57 | check_caller(obj, 2) 58 | obj.__privdict__[self.name] = value 59 | 60 | def __delete__(self, obj): 61 | check_caller(obj, 2) 62 | try: 63 | del obj.__privdict__[self.name] 64 | except KeyError: 65 | raise AttributeError("Private attribute '%s' not set"%self.name) 66 | 67 | 68 | # Private storage for attributes, I think most doors are closed 69 | class PrivateDict(object): 70 | __slots__ = ['owner', 'dic'] 71 | 72 | def __init__(self, owner): 73 | self.owner = owner 74 | self.dic = {} 75 | 76 | def __setitem__(self, key, value): 77 | check_caller(self.owner, 3) 78 | self.dic[key] = value 79 | 80 | def __getitem__(self, key): 81 | check_caller(self.owner, 3) 82 | return self.dic[key] 83 | 84 | def __getattribute__(self, attr): 85 | check_caller(self, 2) 86 | return super(PrivateDict, self).__getattribute__(attr) 87 | 88 | def __setattribute__(self, attr): 89 | check_caller(self, 2) 90 | return super(PrivateDict, self).__getattribute__(attr) 91 | 92 | 93 | # Now, a metaclass to ease usage... 94 | class EnablePrivate(type): 95 | # well, actually, now the metaclass doesn't only ease usage, but 96 | # it has to track which methods were really created on class 97 | # definition and not added later 98 | #def __init__(cls, name, bases, dict): 99 | 100 | 101 | def __call__(cls, *args, **kwds): 102 | new = cls.__new__(cls, *args, **kwds) 103 | new.__privdict__ = PrivateDict(new) #FIXME: don't like crossreferences 104 | cls.__init__(new, *args, **kwds) 105 | return new 106 | 107 | 108 | 109 | # And a function to ease even more 110 | def private(*args): 111 | # this function gets the list of private attributes at args, and 112 | # build a dict with the PrivateAttribute descriptors 113 | attrs = dict((name, PrivateAttribute(name)) for name in args) 114 | 115 | # then makes a new function that will act as a metaclass but 116 | # automatically updates the attributes dict with the private 117 | # attributes before calling the real metaclass 118 | def fake_metaclass(name, bases, dict): 119 | dict.update(attrs) 120 | # mark original methods... have to find a better way to do 121 | # this 122 | methods = [] 123 | for k, v in dict.items(): 124 | if isinstance(v, types.FunctionType): 125 | methods.append(k) 126 | dict['methods'] = methods 127 | return EnablePrivate(name, bases, dict) 128 | return fake_metaclass 129 | 130 | 131 | # Now, some test code 132 | class Test(object): 133 | __metaclass__ = private('foo', 'bar') 134 | 135 | def __init__(self): 136 | self.foo = None 137 | self.bar = None 138 | self.wow = None 139 | 140 | def set_foo(self, value): 141 | self.foo = value 142 | self.bar = "and I am bar" 143 | 144 | def get_foo(self): 145 | return self.foo 146 | 147 | 148 | 149 | def testit(): 150 | o = Test() 151 | a = Test() 152 | 153 | # First, the obvious, the setter should work 154 | o.set_foo('I am foo in o') 155 | a.set_foo('I am foo in a') 156 | 157 | # and the getter too 158 | try: 159 | print "Testing getter: ", 160 | assert o.get_foo() == 'I am foo in o' 161 | assert a.get_foo() == 'I am foo in a' 162 | print 'OK' 163 | except PrivateAttributeError, msg: 164 | print 'FAIL', msg 165 | 166 | # And direct access should not 167 | try: 168 | print "Testing direct access to get: ", 169 | o.foo 170 | a.foo 171 | print 'ERROR' 172 | except PrivateAttributeError, msg: 173 | print 'OK' 174 | 175 | # for set neither 176 | try: 177 | print "Testing direct access to set: ", 178 | o.foo = 'I am not the original foo in o' 179 | a.foo = 'I am not the original foo in a' 180 | print 'ERROR' 181 | except PrivateAttributeError, msg: 182 | print 'OK' 183 | 184 | # it shouldn't work even with super class __getattribute__ method 185 | try: 186 | print "Testing with object.__getattribute__: ", 187 | assert object.__getattribute__(o, 'foo') == 'I am foo in o' 188 | assert object.__getattribute__(a, 'foo') == 'I am foo in a' 189 | print 'ERROR' 190 | except PrivateAttributeError, msg: 191 | print 'OK' 192 | 193 | # and __setattr__ neither 194 | try: 195 | print "Testing with object.__setattr__: ", 196 | object.__setattr__(o, 'foo', 'I am not the original foo in o') 197 | object.__setattr__(a, 'foo', 'I am not the original foo in a') 198 | print 'ERROR' 199 | except PrivateAttributeError, msg: 200 | print 'OK' 201 | 202 | # and it shouldn't work with __dict__ too 203 | try: 204 | print o.__dict__ 205 | print "Testing with __dict__: ", 206 | assert o.__dict__['foo'] == 'I am foo in o' 207 | assert a.__dict__['foo'] == 'I am foo in a' 208 | print 'ERROR' 209 | # the foo descriptor is a class attribute, so should not 210 | # be accessible here 211 | except KeyError, msg: 212 | print 'OK' 213 | 214 | # Making it a bit harder... add my own getter dinamically 215 | def getfoo(self): 216 | return self.foo 217 | 218 | try: 219 | print "Testing with dinamically added getter: ", 220 | Test.getfoo = getfoo 221 | assert o.getfoo() == 'I am foo in o' 222 | #assert a.getfoo() == 'I am foo in a' 223 | print 'ERROR' 224 | # the foo descriptor is a class attribute, so should not 225 | # be accessible here 226 | except PrivateAttributeError, msg: 227 | print 'OK' 228 | 229 | # Now, testing the hard paths... suppose I know the implementation... 230 | try: 231 | print "Testing with __privdict__: ", 232 | assert o.__privdict__['foo'] == 'I am foo in o' 233 | assert a.__privdict__['foo'] == 'I am foo in a' 234 | print 'ERROR' 235 | # the foo descriptor is a class attribute, so should not 236 | # be accessible here 237 | except PrivateAttributeError, msg: 238 | print 'OK' 239 | 240 | # Now, testing the hard paths... suppose I know the implementation... 241 | try: 242 | print "Testing with object.__getattribute and __privdict__: ", 243 | assert object.__getattribute__(o.__privdict__, 'dic')['foo'] == 'I am foo in o' 244 | assert object.__getattribute__(a.__privdict__, 'dic')['foo'] == 'I am foo in a' 245 | print 'ERROR' 246 | # the foo descriptor is a class attribute, so should not 247 | # be accessible here 248 | except PrivateAttributeError, msg: 249 | print 'OK' 250 | 251 | 252 | 253 | 254 | 255 | testit() 256 | 257 | --------------------------------------------------------------------------------