Sujet : Re: extend behaviour of assignment operator
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 10. Jan 2024, 20:40:49
Autres entêtes
Organisation : Stefan Ram
Message-ID : <ast-20240110203859@ram.dialup.fu-berlin.de>
References : 1
Guenther Sohler <
guenther.sohler@gmail.com> writes:
i'd like to extend the behaviour of the assignment operator
The following attempt is just a proof of concept, as it will
not handle properly all possible code. To do something similar
in a more general way, use "import ast", parse the code into
an AST and then search the AST for assignements and insert
code to change the name attribute after them.
import re
class thing: pass # all things pass
code = r'''
a = thing()
print( a.name )
b = a
print( b.name )
'''
code = \
re.sub\
( r'((?:^|\n)(\s*)([\w_]+)\s*=.*(\n|$))', r'\1\2\3.name="\3"\n', code )
exec( code )