Unexpected behavior with class and instance variables...

tracy s. ruggles trace at reinventnow.com
Wed Jul 11 02:15:57 EDT 2001


I'm trying to build a wrapper for any given function and noticed some odd
behavior with using class variables instead of instance variables.

I've included the script below... It chokes on trying to call the function
that was built using class variables as defaults, instead of instance
variables.

The error message I get is:
    TypeError: myFunction() takes exactly 1 argument (2 given)

This happens when the function built using class variables is called.  Doing
a post-mortem in the IDE shows that there really is only 1 argument being
passed into the function, but for some reason it thinks there is 2.  This
doesn't happen with the function built using instance variables.

Why?

--Tracy
(trace at reinventnow.com)


---/  CODE BELOW  /---

def myFunction(a): return str(a)

class Function:
    def __init__(self, f):
        self._f = f
    def __call__(self, *args):
        results = []
        for arg in args:
            results.append(self._f(arg))
        if len(results) is 1: return results[0]
        return results
        
def build(f, fClass=Function):
    return fClass(f)

class AppWithInstanceDefaults:
    """Application that sets defaults in __init__"""
    def __init__(self):
        """Set default values for instance"""
        self._defaultFunction = myFunction
        self._defaultFunctionClass = Function
    def makeFunction(self):
        """Create a meta-function with the builder function
            and this instance's defaults"""
        return build(self._defaultFunction, self._defaultFunctionClass)

class AppWithClassDefaults(AppWithInstanceDefaults):
    """Application that has class variables as defaults"""
    _defaultFunction = myFunction
    _defaultFunctionClass = Function
    def __init__(self):
        """We don't want no stinkin' instance variables"""
        pass

def test():
    print "-"*20
    data = 42
    
    IDApp = AppWithInstanceDefaults()
    IDFunction = IDApp.makeFunction()
    
    CDApp = AppWithClassDefaults()
    CDFunction = CDApp.makeFunction()
    
    print IDFunction(data)
    print CDFunction(data)

if __name__ is "__main__": test()




More information about the Python-list mailing list