473,507 Members | 2,416 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get rid of recursive call __getattr__

How can I get rid of recursive call __getattr__ inside this method, if
i need to use method or property of the class?

Dec 14 '05 #1
13 3472
Pelmen wrote:
How can I get rid of recursive call __getattr__ inside this method, if
i need to use method or property of the class?

Sorry, but I don't understand your question. Which recursive calls to
__getattr__ ? __getattr__ is only called if a/ it's defined and b/ the
attribute has not been found (see below).

Have you overriden __setattr__ or __getattribute__ ? If yes, please read
the corresponding sections of the Fine Manual.

class Toto(object): .... def __init__(self, name):
.... self.name = name
.... def __getattr__(self, attname):
.... print "__getattr__ called for %s" % attname
.... return "%s doesn't exists" % attname
.... t = Toto('toto')
t.name = name Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'name' is not defined t.name 'toto' t.age

__getattr__ called for age
"age doesn't exists"

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Dec 14 '05 #2

Pelmen wrote:
How can I get rid of recursive call __getattr__ inside this method, if
i need to use method or property of the class?


Hi Pelmen,

Having read the docs included with my Python distribution on
__getattr__, I don't see yet how you will get recursive calls to the
method... (It's called only when the attribute cannot be looked up via
normal means)

If you are seeing recursive calls to __getattr__, perhaps you can
highlight the problem with some sample-code?

regards,

--Tim

Dec 14 '05 #3
thanks, i should been read more closely

Dec 14 '05 #4
thanks, i understood my mistake
i try to get attribute, that wasn't defined

Dec 14 '05 #5
Pelmen wrote:
How can I get rid of recursive call __getattr__ inside this method, if
i need to use method or property of the class?

The usual mistake here is to write a __getattr__() implementation that
references an undefined self-relative name, which leads to a recursive
call of __getattr__(), which ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 14 '05 #6
as __repr__ for example?

Dec 14 '05 #7
thanks, i found the problem

Dec 14 '05 #8
>>> class Test:
def __getattr__(self, attr):
print attr

def foo(x):
print x
t = Test()
print t

__str__

Traceback (most recent call last):
File "<pyshell#23>", line 1, in -toplevel-
print t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?

Dec 14 '05 #9
Pelmen wrote:
class Test: **********def*__getattr__(self,*attr):
************print*attr

**********def*foo(x):
************print*x
t = Test()
print t __str__

Traceback (most recent call last):
**File*"<pyshell#23>",*line*1,*in*-toplevel-
****print*t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?


By seemingly not returning anything your __getattr__() method actually
returns None. Instead you should raise an AttributeError when your
__getattr__() encounters the name of an attribute it doesn't handle.
Let's assume Test.__getattr__() should implement an attribute 'alpha' and
nothing else:
class Test: .... def __getattr__(self, name):
.... print "looking up", name
.... if name == "alpha":
.... return 42
.... print "lookup failed for", name
.... raise AttributeError
.... print Test()

looking up __str__
lookup failed for __str__
looking up __repr__
lookup failed for __repr__
<__main__.Test instance at 0x4029248c>

When the lookup fails in the instance it is deferred to the class.
By the way, new-style classes handle __special__ methods a bit differently
-- try deriving Test from object

class Test(object):
# same as above

to see the difference.

Peter

Dec 14 '05 #10
thanks, now all clear

Dec 14 '05 #11
Peter Otten wrote:
Pelmen wrote:

>class Test:
def __getattr__(self, attr):
print attr

def foo(x):
print x

>t = Test()
>print t


__str__

Traceback (most recent call last):
File "<pyshell#23>", line 1, in -toplevel-
print t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?

By seemingly not returning anything your __getattr__() method actually
returns None. Instead you should raise an AttributeError when your
__getattr__() encounters the name of an attribute it doesn't handle.
Let's assume Test.__getattr__() should implement an attribute 'alpha' and
nothing else:

class Test:


... def __getattr__(self, name):
... print "looking up", name
... if name == "alpha":
... return 42
... print "lookup failed for", name
... raise AttributeError


or, rather better IMHO,

raise AttributeError("lookup failed for %s" % name) ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Dec 14 '05 #12
Pelmen wrote:
class Test:
def __getattr__(self, attr):
print attr

def foo(x):
print x

t = Test()
print t
__str__

Traceback (most recent call last):
File "<pyshell#23>", line 1, in -toplevel-
print t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?


Yes. Or subclass "object" as it has a default __str__ already.

(By the way, you do realize that the NoneType message comes because your
__getattr__ is returning None, don't you? So technically you could also
return a real value (in this case a callable) and it would also work,
though it's very likely not what you wanted.

class Test:
def __getattr__(self, name):
def callable_attribute():
return 'i am attr %s' % name
return callable_attribute
t = Test()
print t

i am attr __str__

-Peter

Dec 14 '05 #13
Steve Holden wrote:
Peter Otten wrote:
Pelmen wrote:

>> class Test:
def __getattr__(self, attr):
print attr

def foo(x):
print x
>> t = Test()
>> print t
__str__

Traceback (most recent call last):
File "<pyshell#23>", line 1, in -toplevel-
print t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?


By seemingly not returning anything your __getattr__() method actually
returns None. Instead you should raise an AttributeError when your
__getattr__() encounters the name of an attribute it doesn't handle.
Let's assume Test.__getattr__() should implement an attribute 'alpha' and
nothing else:

> class Test:

... def __getattr__(self, name):
... print "looking up", name
... if name == "alpha":
... return 42
... print "lookup failed for", name
... raise AttributeError

or, rather better IMHO,

raise AttributeError("lookup failed for %s" % name)


or still better in IMNSHO:
raise AttributeError("%s object has no attribute %s" %
\ (self.__class__.__name__,
name))

(which is the 'standard' AttributeError message)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Dec 15 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2869
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays...
4
2417
by: Nicolas Vigier | last post by:
Hello, I have in my python script a function that look like this : def my_function(arg1, arg2, opt1=0, opt2=1, opt3=42): if type(arg1) is ListType: for a in arg1: my_function(a, arg2,...
4
9035
by: Victor | last post by:
Hello, I've got a situation in which the number of (valid) recursive calls I make will cause stack overflow. I can use getrlimit (and setrlimit) to test (and set) my current stack size. ...
9
13151
by: Bill Borg | last post by:
Hello, I call a function recursively to find an item that exists *anywhere* down the chain. Let's say I find it five layers deep. Now I've got what I need and want to break out of that whole...
5
2390
by: glomde | last post by:
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some...
13
2115
by: ArseAssassin | last post by:
I'm using minidom to parse XML and to simplify accessing child nodes, I'm trying to implement __getattr__ for the Node class. Yes, I know what most of you will think of that; I'll just have to be...
4
2110
by: ThEoNeAnDOnLy | last post by:
I recently had an issue with my recursive project in class. Here is the code. // Recursion.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include...
3
4216
by: from.future.import | last post by:
Hi, I encountered garbage collection behaviour that I didn't expect when using a recursive function inside another function: the definition of the inner function seems to contain a circular...
3
2327
by: Davy | last post by:
Hi all, Sometimes I need to pass same parameter in recursive function. From my point of view, the style is redundant, and I don't what to use some global style like self.A, self.B, Is there any...
0
7223
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7111
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5623
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5042
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3191
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1542
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.