Python 2.5中的类装饰器? [英] Class decorators in Python 2.5?

查看:78
本文介绍了Python 2.5中的类装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使类装饰器 Google App Engine 上运行, Python 2.5 $ b

或者让我改述一下:是否有可能从它已经执行的同一个进程中改变Python解析器的行为?示例:

good.py:

  alter_python_parser()
import bad

bad.py:

  @decorated 
class Foo(object):pass

或者这可能显然不可能。



解释:我想使用第三方库大量使用类装饰器,并且不想分叉并维护我自己的版本。另一种方法是使用较新的python在 Typhoon App Engine 上运行我的代码,但是我担心Google不会将它的Python版本升级为loooong time ...

编辑: $ b

如何创建新式导入钩子那会在运行中执行字符串替换并从内存加载模块?这应该是可能的。我会试一试,如果没有实现的话。



但是我怎样才能解析 Python 2.6 + 代码来自 Python 2.5 ?有没有一个Python的解析器?什么是 PYPY 使用?

解决方案

装饰器只是语法糖。只需更改装饰器使用的实例,即


$ b $ class Foo(object):pass

变成

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

t,实际上,改变解析器。



尽管如此,您可以使用 ast模块(在新版本的Python中)。


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?

解决方案

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).

这篇关于Python 2.5中的类装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆