How do I extend a class that I never instantiate myself?

Chris Angelico rosuav at gmail.com
Sun Oct 11 19:53:52 EDT 2015


On Mon, Oct 12, 2015 at 10:09 AM,  <speeze.pearson at gmail.com> wrote:
> On Saturday, October 10, 2015 at 11:32:24 PM UTC-7, Chris Angelico wrote:
>> If you REALLY want to look like Ruby, <snip>
>
> Ha! This thread has provided so many interesting monkey-patching techniques,
> but this might be the most perverse. Very cute.

Thank you for taking it in its proper light.

To be quite frank, I don't know that this is even supported. Can
anyone confirm or deny?

Simple test:

def deco(f): print(globals()[f.__name__])
foo = bar = "old"
@deco
def foo(x): pass
@deco
class bar(object): pass

If it prints 'old' twice, the trick works. I tested it on PyPy 2.4,
Jython 2.5, and CPython 2.7 and 3.6. More importantly, though, the
docs always describe decorators as being equivalent to defining a
function and then reassigning:

https://www.python.org/dev/peps/pep-0318/#motivation
https://docs.python.org/2/glossary.html#term-decorator
https://docs.python.org/2/reference/compound_stmts.html#function
https://docs.python.org/3/glossary.html#term-decorator
https://docs.python.org/3/reference/compound_stmts.html#function

So I think this is about on par with tinkering with sys._getframe to
make stuff work :)

ChrisA



More information about the Python-list mailing list