strange behaviour with decorators.

A

Antoon Pardon

I tried the following program:

def positive(f):

def call(self, u):

if u < 1:
print 'Not Positive'
raise ValueError
return f(self, u)

return call

class Incrementor:

def __init__(self, val=0):
self.value = val

@positive
def __call__(self, term = 1):
print 'incrementing'
self.value += term
return self.value

inc = Incrementor(0)
try:
print inc(1)
print inc()
print inc(3)
print inc(-2)
except:
pass


And it gave me the following result:

incrementing
1


Now although this behaviour was surprising after somethought
I think I may understand why things go wrong, but I certainly
don't understand the result I got. I would think an error like:

TypeError: call() takes exactly 2 arguments (1 given)

would have been more appropiate.


Am I missing something?
Is it a bug?
Maybe both?
 
D

Diez B. Roggisch

Now although this behaviour was surprising after somethought
I think I may understand why things go wrong, but I certainly
don't understand the result I got. I would think an error like:

TypeError: call() takes exactly 2 arguments (1 given)

would have been more appropiate.


Am I missing something?
Is it a bug?
Maybe both?

Maybe I'm missing something - but I exactly get that error if I don't use
that try: except: of yours:

For this

-----------------
def positive(f):
def call(self, u):

if u < 1:
print 'Not Positive'
raise ValueError
return f(self, u)

return call

class Incrementor:
def __init__(self, val=0):
self.value = val

@positive
def __call__(self, term = 1):
print 'incrementing'
self.value += term
return self.value

inc = Incrementor(0)

print inc(1)
print inc()
print inc(3)

--------------------

I get this result:
deets@kumquat:~$ python2.4 /tmp/test.py
incrementing
1
Traceback (most recent call last):
File "/tmp/test.py", line 24, in ?
print inc()
TypeError: call() takes exactly 2 arguments (1 give
 
A

Antoon Pardon

Op 2005-02-09 said:
Maybe I'm missing something - but I exactly get that error if I don't use
that try: except: of yours:

Ah, yes, the penny dropped. The try: except where there because
originally there were other statements I wanted to test and I
didn't want the raise exception by the inc(-2) stop the script.
I completely forget to consider it would also catch the
error I was expecting.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top