473,657 Members | 2,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

@staticmethod, backward compatibility?

How can I write code to take advantage of new decorator syntax, while
allowing backward compatibility?

I almost want a preprocessor.

#if PYTHON_VERSION >= 2.4
@staticmethod
....
Since python < 2.4 will just choke on @staticmethod, how can I do this?

Sep 27 '05 #1
2 1876
Neal Becker wrote:
How can I write code to take advantage of new decorator syntax, while
allowing backward compatibility?

I almost want a preprocessor.

#if PYTHON_VERSION >= 2.4
@staticmethod
...

Since python < 2.4 will just choke on @staticmethod, how can I do this?


It seems to me that no matter what you do, if it's not done with an
external processing tool which requires no changes in the source code,
the result will be much uglier than if you just used the pre-2.4
decorator syntax:

def meth():
pass
meth = staticmethod(me th)
-Peter
Sep 27 '05 #2
Neal Becker wrote:
How can I write code to take advantage of new decorator syntax, while
allowing backward compatibility?

I almost want a preprocessor.

#if PYTHON_VERSION >= 2.4
@staticmethod
...
Since python < 2.4 will just choke on @staticmethod, how can I do this?

Here's one way to do it. The restrictions are:

it only works on modules, so you can't use decorators in the
main script;
it only handles one decorate per function (but shouldn't be
too hard to extend);
decorators are assumed to only occupy a single line.

Example of use:

----- example.py --------
import decorate23
import test

test.C().fred(' it', 'works')
----- end example.py ----

----- test.py -----------
class C:
@staticmethod
def fred(a, b):
print a, b
return None

@classmethod
def freda(cls, a, b):
print a, b
return None
----- end test.py -------

The contents of decorate23 are, of course, left as an exercise
for the reader.













Only kidding:

----- decorate23.py -----
# Automatically apply decorators for pre-2.4 code
import sys
import re
if sys.version_inf o < (2,4):
from imputil import _compile, _suffix_char
import imp, sys, marshal, struct, __builtin__
import imputil

PATTERN = re.compile('^(? P<indent>[\\s]*)@(?P<decorato r>.*)\n'
'(?P<body>\\1de f (?P<id>[a-zA-Z_0-9]+)\\(.*(?:\n\\1 .*)*)',
re.MULTILINE)
def autodecorate(so urce):
def replace(match):
decorator = match.group('de corator')
indent = match.group('in dent')
id = match.group('id ')
body = match.group('bo dy')

return "%(body)s\n%(in dent)s%(id)s = %(decorator)s(% (id)s)\n" % locals()

return PATTERN.sub(rep lace, source)

def hook_compile(pa thname, timestamp):
"""Compile (and cache) a Python source file.

The file specified by <pathname> is compiled to a code object and
returned.

Presuming the appropriate privileges exist, the bytecodes will be
saved back to the filesystem for future imports. The source file's
modification timestamp must be provided as a Long value.
"""
codestring = open(pathname, 'rU').read()

if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
codestring = autodecorate(co destring)

code = __builtin__.com pile(codestring , pathname, 'exec')

# try to cache the compiled code
try:
f = open(pathname + _suffix_char, 'wb')
except IOError:
pass
else:
f.write('\0\0\0 \0')
f.write(struct. pack('<I', timestamp))
marshal.dump(co de, f)
f.flush()
f.seek(0, 0)
f.write(imp.get _magic())
f.close()

return code

imputil._compil e = hook_compile
imputil.ImportM anager().instal l()
----- end decorate23.py -

The overhead shouldn't be too bad as the hook will only kick in when
the code needs recompiling, but the line numbers in tracebacks
refer to the modified code so they'll be slightly out.
Sep 27 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1649
by: Vyacheslav Lanovets | last post by:
Hello, All! Installed VS 2005... What is annoying is that project files are not backward compatible. For instance, EVC4 vcp files are backward compatible with EVC3 and can be used simultaneously (moreover I could run EVC3 and EVC4 with the same workspace at the same time). vcproj files are in xml, why not to allocate separate node to store
1
1916
by: Dev | last post by:
Dear Friends, I have created VC++.NET dll by VS.NET2003.Is it possible to use this dll(vs.net2003) into C# version (Vs.net2002)? Is there backward compatibility? If so ..How do to this?..If anyone knows ..please let me know. Thanks, Dev
2
6195
by: Dominic | last post by:
Hi everybody, I'm planning to use serialization to persist an object (and possibly its child objects) in my application. However, I'm concerned about the backward compatibility issue. I'm evaluating if we can easily resolve this issue. For example, I have a class MyClass consisting of 100 fields.
1
1658
by: MLibby | last post by:
I'm a Netscape newbie and am using it for backward compatibility testing. How do I debug javascript in Netscape? I set Netscape as the default debugger (design mode | file | Browse With) and I am able to debug code behind. However, when I try to debug the .js file the debugger doesn't hit the breakpoints! Any ideas? Mike --
3
3958
by: Madhu | last post by:
We are having a dll backward compatibility issue since we migrated to .NET 2005. As part of our product, we build a dll which is used by other products. Everything was fine when we were build it on VC6. We upgraded our compiler to ..NET 2005 for our new version. The new dll fails to load, we get a runtime error: R6034. We managed to work it around by creating a manifest file for the loading executable, but this is not an acceptable work...
0
1425
by: bhargav mandlem | last post by:
hi friends i have created VC++.NET dll by VS.NET2003.Is it possible to use this dll(vs.net2003) into C# version (Vs.net2002)? Is there backward compatibility? If so ..How do to this?..If anyone knows ..please let me know. Regards Bhargav
2
1834
by: Ernesto Bascón | last post by:
Hi: I've read some about the pimpl idiom and I know that it provides safe ABI backward compatibility on shared libraries. Let's consider the following definitions: template <class T> class A {
7
1845
by: Ernesto Bascón | last post by:
Hi everybody: I want to develop a library that uses heavily templates. Is there an idiom or some tips about things that I should care of in order to provide backward compatibility with my library? (i. e., if I release new versions of my library, what things must I consider to allow the applications that use it, run with no recompilation? There is some idiom that helps to handle that (like the
5
12415
by: jaad | last post by:
Hello, I have a database that was written in access 2007 on my pc. I wanted to work off site with the database so I uploaded it onto my laptop which is loaded with access 2010 beta. When I finished working with the database and return it to my pc(which has access 2007) I can't get it open because Access say that the file is not the right format. Does anyone have a way to work around this compatibility problem? So you know I...
0
8395
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7330
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4306
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.