How do I give a decorator acces to the class of a decorated function

Peter Otten __peter__ at web.de
Thu Sep 5 10:31:04 EDT 2019


Antoon Pardon wrote:

> On 5/09/19 15:30, Peter Otten wrote:

>> Can you provide some context?
> 
> Sure I am researching the possibility of writing an easy to use
> lexing/parsing tool. The idea is to write your lexer/parser as
> follows:
> 
> class Calculator(metaclass = ...):
>     def __init__(self):
>         self.names = set()
>         self.table = {}
> 
>     @token(r'\d+')
>     def NUMBER(self, st):
>         return int(st)
> 
>     @token(r'\w+')
>     def VAR(self, st):
>         self.names.add(st)
>         return st
> 
>     @production(r"VAR '=' NUMBER")
>     def assign(self, prd):
>         name = prd[0]
>         val = prd[1]
>         if name in self.names:
>             self.table[name] = value
>         else:
>             raise CalcError("variable (%s) not available" % name)
> 
> calc = Calculator()
> calc("a = 7")
> 
> So the token en production decorators register a regex/prodcution with
> a specific method to be called in specific circumstances when parsing
> a string.
> 
> So I need the lexing and parsing algorithms available to this class,
> either by adding methods to the class or by making a subclass of the
> class where they are implemented.

Ok, that looks like a nice interface to me, and I don't expect the metaclass 
dance to make it harder to implement than necessary ;)





More information about the Python-list mailing list