Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class decorators in Python 2.5?

Is there a way I can make class decorators work on Google App Engine, which is limited to Python 2.5?

Or let me rephrase that: is it possible to alter the behavior of Python's parser from the same process that it is already executing? Example:

good.py:

alter_python_parser()
import bad

bad.py:

@decorated
class Foo(object): pass

Or is this maybe just plainly impossible.

Explanation: I want to use a third party library that heavily uses class decorators, and don't want to fork it and maintain my own version. An alternative would be to run my code on Typhoon App Engine with a newer python, but I fear Google won't upgrade their Python version for a loooong time...

EDIT:

How about creating a new-style import hook that would do string substitution on-the-fly and load the module from memory? That should be possible. I'll give it a try, if there's no implementation already out there.

But how can I parse Python 2.6+ code from Python 2.5? Is there a python-only parser? What does PYPY use?

like image 714
Attila O. Avatar asked Nov 29 '10 19:11

Attila O.


People also ask

Can we use decorators on class in Python?

In Python, decorators can be either functions or classes. In both cases, decorating adds functionality to existing functions. When we decorate a function with a class, that function becomes an instance of the class. We can add functionality to the function by defining methods in the decorating class.

Can we use 2 decorators in Python?

Python allows us to implement more than one decorator to a function.

What are decorators in Python 3?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.


1 Answers

Decorators are just syntactic sugar. Just change instances of decorator usage, that is,

@decorated
class Foo(object): pass

becomes

class Foo(object): pass
Foo = decorated(Foo)

You can't, realistically, change the parser.

Though, you could automate the above process using the ast module (in a new version of Python).

like image 165
dan_waterworth Avatar answered Sep 23 '22 07:09

dan_waterworth