Python and Jython are kinda different

Dave Benjamin ramen at lackingtalent.com
Fri Jan 9 21:39:12 EST 2004


In article <mailman.257.1073699457.12720.python-list at python.org>, Jp Calderone wrote:
>   All generators can be re-written with classes using the iterator protocol. 
> Here's a simple example:

Thanks for the nice example. Unfortunately:

Jython 2.1 on java1.4.2_01 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> execfile('your-nice-example.py')
>>> for j in FooGen(): print j
...
Traceback (innermost last):
  File "<console>", line 1, in ?
AttributeError: __getitem__

Bring back any memories of the days before generators? ;)

>>  - properties
> 
>   This is getting closer, I think.  More generator, descriptors are pretty
> honkin' fundamental these days.  On the other hand, most behavior
> acheivable with properties can be achieved with __g/setattr__, albeit it
> quite as conveniently.

Yes, but from my experience the property() builtin is so much more
convenient than __get/setattr__ that I am much more likely to use properties
in CPython. With Jython, I have to overcome my laziness, since it means
writing a fair bit of boilerplate. (example follows)

>>  - getattr/getitem behavior (which is even different from CPython 2.1)
> 
>   I guess I haven't used Jython enough to know what's going on here.

Here's an example. I sometimes find it useful to create dictionaries that
allow either attribute or item access, a la JavaScript/ActionScript. In
CPython, I can use the (comment to a) recipe from ASPN:

class attrdict(dict):
    def __getattr__(self, name):
        return self[name]
            
    def __setattr__(self, name, value):
        self[name] = value
                        
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52313)

This seems like it would be a very simple port to Jython, right? It's
actually a bit hairy. In order to get it to work, I had to do the following:

class attrdict(UserDict):
    "Dictionary that allows keys to be used as object attributes."
    
    def __init__(self, dict=None, **kwds):
        """attrdict() constructor (behaves like Python 2.3's dict()).
        Optionally takes a source dictionary or keyword arguments."""

        if hasattr(dict, 'items'):
            UserDict.__init__(self, dict)
        else:
            UserDict.__init__(self)
                                        
            if dict is not None:
                for key, value in dict:
                    self[key] = value
                    
        if kwds:
            self.update(kwds)
                                        
    def __getattr__(self, name):
        if self.__dict__.has_key(name):
            raise AttributeError, name
        elif name == '__members__':
            return self.keys()
        elif name.startswith('__') and name.endswith('__'):
            raise AttributeError, name
        else:
            return self[name]
                                
    def __setattr__(self, name, value):
        if name == 'data':
            self.__dict__[name] = value
        else:
            self[name] = value
                    
    def __delattr__(self, name):
        del self[name]

Whew! Now we're rolling with any version of CPython or Jython 2.1 and up. I
wish I could explain to you how much I had to screw with this to get it to
work. It turns out that the constructor for UserDict tries to create an
attribute called "data", which calls my custom __setattr__, and it gets
stuck in an infinite loop. Many combinations and stack exceptions later, I
finally got what used to be a five-line class working in Jython.

Now, I hope you understand why I'm more privy to properties in CPython. =)

>>  - type factories being classes
> 
>   This seems pretty important to me, probably the most important on the
> list.  Metaclasses existed before 2.2, but not without writing an extension
> module.

Hmmm... well, metaclasses would be nice, too, but mostly I was thinking of
whether you subclass "dict" or "UserDict" or "types.DictType", and whether
or not things like "str.join" are available. The former, as you can see, can
make a big difference in how you code things. The latter isn't so significant.

>>  - dictionary support for "in" keyword
> 
>   This seems pretty trivial to me. It's just a transformation of
> dict.has_key().

Yep, and there were many such transformations I had to hunt down and fix by
hand when trying to port the "sets" module. A pretty small module, too. It
was error-prone, and I actually missed a serious performance error when I
posted the patch to c.l.p. If anyone is interested, I can post a better
patch, or just send you the file (contact me by email - r!a at m#e%n AT
r^a at m#e&n!f at e&s#t PUNTO com - remove the line noise of course).

>> > I believe GvR said that PyPy might (might!) become a sort of
>> > executable standard for Python in the future, though.
>> 
>> I think that's an impressive idea, but it almost seems like the resources
>> spent in keeping PyPy and CPython in parallel could be better spent keeping
>> Jython and CPython in parallel, seeing as nobody is calling PyPy "Python"
>> currently.
> 
>   Can't say I agree here, probably because I don't much care about Java ;)
> I think PyPy has a lot more bang for the buck for your average Python
> programmer.  Jython might be nice to bring in some of the Java people, or
> make some of that Java work easier when you absolutely have to use it, but
> for your average Python application, it hardly enters into the picture. 
> PyPy, on the other hand opens up a lot of possibilities for future
> improvements to the language (because it is easier to prototype new features
> in Python than in C) as well as improvements to existing features.

Well, I have to admit I'm a bit biased. I work in a Java team, and I've been
trying to incorporate Python into the existing infrastructure for the past
year or so. So, personally, I'm not the world's biggest Java fan, and I find
PyPy much more interesting, but Jython has more immediate usefulness.
However, I do find myself doing a lot of extra work to keep my code portable
between Jython and CPython, since it facilitates reuse.

I agree that PyPy presents new possibilities for language experimentation,
and being a total language nerd myself, I'm all for it. =)

However, I just want to make the point that Jython is becoming less and less
"Python" as the evolution of CPython begins to affect the actual style in
which Python code is written. And this makes the popular claim, that Python
is the language, and CPython and Jython are two implementations, a bit
misleading.

But it's a lot easier to complain than to contribute. That I'll readily
admit. =)

Thanks,
Dave

-- 
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :



More information about the Python-list mailing list