"as" keyword woes

Matimus mccredie at gmail.com
Wed Dec 3 20:15:21 EST 2008


> What I want to understand is why this parser change was necessary in
> order to enable new 2.6/3.0 features.  Was this change potentially
> avoidable?

Does it really matter? The change occurred and it isn't going to go
back. What you should be asking yourself is whether the affect it had
on your code could have been avoided. What could you have done to
prevent your current situation?

> Couldn't we have continued along just fine using a smarter parser
> without elevating "as" to reserved status (and thus potentially breaking
> a 10+ years of existing code)?

Nothing broke your code. It works just fine under the version it was
developed for. Who forced you to upgrade to python2.6?

'as' was already coming close to being a keyword with its use in
import statements. It be came a full fledged keyword to support
context managers:

with open('filename.x', 'w') as fout:
  # do stuff

> (Unfortunately, our project may now have to maintain a branch at 2.5.x
> in order to preserve compatibility with existing third-party scripts &
> infrastructure which routinely rely upon "as" as an object method.
> Sigh.)

Not necessarily. You can do something like this:

import sys
import warnings

class MyClass(object):
    def new_as(self): # call this something appropriate, it is your
new 'as' method
        pass  # do what 'as' does

    if sys.version[:3] <= '2.5':
        def _old_as(self):
            warnings.warn(
                    DeprecationWarning(
                            'This method is deprecated, use `new_as`
instead'))
            return self.new_as()
        exec 'as = _old_as'

You could even write a metaclass that does this (a little more
elegantly). Your users will get a nice warning telling them not to use
the 'as' method anymore. It will work in both code bases, and you can
schedule to remove it at some later version after customers have had
the opportunity to remove 'as' from their code.

Matt



More information about the Python-list mailing list