views:

110

answers:

1

I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following statement is encountered:

if __client != None # __client is an instance of the ClientProxy class

raise AttributeError(attr) is called in __getattr__(), because self.__baseClient doesn't have __ne__ attribute. It's important to mention that I cannot upgrade because jython is a part of a system. Is there a way to get around this issue?

class ClientProxy:
    def __init__(self, baseClient):
        self.__baseClient = baseClient
        self.__initialised = 1

    def __getattr__(self, attr):
        if not self.__dict__.has_key('_ClientProxy__initialised'):
            raise AttributeError(attr)
        else:
            if hasattr(self.__baseClient, attr):
                return getattr(self.__baseClient, attr)
            else:
                raise AttributeError(attr)


    def __setattr__(self, attr, val):
        if not self.__dict__.has_key('_ClientProxy__initialised'):
            self.__dict__[attr] = val
            return

        if hasattr(self.__baseClient, attr):
            self.__baseClient.__setattr__(attr, val)
        else:
            self.__dict__[attr] = val

Thanks a lot!

A: 
if __client != None:

For testing against specific instances such as None, it's idiomatic to use the identity operator:

if __client is not None:

This will avoid the problem of calling comparators.

However, the fact that __getattr__ raises AttributeError should not be a problem. The comparator should call getattr speculatively for __cmp__ (__ne__ first on newer Pythons), and if it gets an AttributeError it is supposed to silently swallow it and fall back to identity comparison instead. Why does the AttributeError cause a problem in your case?

bobince
After posting this question I noticed that AttributeError actually is raised three times - for `__ne__`, for `__coerce__` and for `__cmp__` in that order, but it's not causing any problems.I left the question just to understand what is going on.Thanks for the quick and informative answer!
DChrome