Questions tagged [getattr]

getattr is a Python built-in function used to access a named attribute on an object.

getattr
Filter by
Sorted by
Tagged with
586 votes
8 answers
227k views

Difference between __getattr__ and __getattribute__

I am trying to understand when to define __getattr__ or __getattribute__. The python documentation mentions __getattribute__ applies to new-style classes. What are new-style classes?
Yarin's user avatar
  • 179k
400 votes
15 answers
373k views

What is & How to use getattr() in Python?

I read an article about the getattr function, but I still can't understand what it's for. The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop....
Terence Ponce's user avatar
276 votes
4 answers
137k views

Understanding the difference between __getattr__ and __getattribute__

I am trying to understand the difference between __getattr__ and __getattribute__, however, I am failing at it. The answer to the Stack Overflow question Difference between __getattr__ vs ...
user225312's user avatar
  • 129k
231 votes
3 answers
114k views

How do I override __getattr__ without breaking the default behavior?

How do I override the __getattr__ method of a class without breaking the default behavior?
sheats's user avatar
  • 33.9k
172 votes
4 answers
76k views

How do I call setattr() on the current module?

What do I pass as the first parameter "object" to the function setattr(object, name, value), to set variables on the current module? For example: setattr(object, "SOME_CONSTANT", 42); giving the ...
Matt Joiner's user avatar
150 votes
9 answers
72k views

__getattr__ on a module

How can implement the equivalent of a __getattr__ on a class, on a module? Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an ...
Matt Joiner's user avatar
144 votes
6 answers
134k views

How do I implement __getattribute__ without an infinite recursion error?

I want to override access to one variable in a class, but return all others normally. How do I accomplish this with __getattribute__? I tried the following (which should also illustrate what I'm ...
Greg's user avatar
  • 46.2k
81 votes
5 answers
95k views

How to use __setattr__ correctly, avoiding infinite recursion

I want to define a class containing read and write methods, which can be called as follows: instance.read instance.write instance.device.read instance.device.write To not use interlaced classes, my ...
Alex's user avatar
  • 43.3k
79 votes
5 answers
43k views

__getattr__ for static/class variables

I have a class like: class MyClass: Foo = 1 Bar = 2 Whenever MyClass.Foo or MyClass.Bar is invoked, I need a custom method to be invoked before the value is returned. Is it possible in ...
Tuxdude's user avatar
  • 48.5k
55 votes
4 answers
44k views

Call method from string

If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it: class CallMe: # Class def App(): # Method one ...
Sirupsen's user avatar
  • 2,105
45 votes
3 answers
36k views

How to launch getattr function in python with additional parameters?

I want to call some unknown function with adding parameters using getattr function. Is it possible?
megido's user avatar
  • 4,225
40 votes
3 answers
17k views

What is the relationship between __getattr__ and getattr?

I know this code is right: class A: def __init__(self): self.a = 'a' def method(self): print "method print" a = A() print getattr(a, 'a', 'default') print ...
zjm1126's user avatar
  • 65.1k
33 votes
5 answers
36k views

getting dynamic attribute in python [duplicate]

I have and object with an pseudo or special attribute that can be named in three different ways (Note: I don't control the code which generates the object) The value in the attributes (depending ...
rhormaza's user avatar
  • 507
32 votes
5 answers
15k views

Recursively access dict via attributes as well as index access?

I'd like to be able to do something like this: from dotDict import dotdictify life = {'bigBang': {'stars': {'planets': []} } } dotdictify(life) # This ...
30 votes
3 answers
44k views

Python using getattr to call function with variable parameters

I'm using getattr to call different functions depending on a variable. Im doing something like that: getattr(foo, bar) () That works, calling functions like foo.bar() My problem is that I have '...
lcorral's user avatar
  • 305
24 votes
1 answer
27k views

How to iterate through a module's functions [duplicate]

I have this function call after importing foo.py. Foo has several methods that I need to call e.g. foo.paint, foo.draw: import foo code if foo: getattr(foo, 'paint')() I need to use a while ...
lobjc's user avatar
  • 2,891
20 votes
1 answer
14k views

'super' object not calling __getattr__

I have one object wrapped inside another. The "Wrapper" accesses the attributes from the "Wrapped" object by overriding __getattr__. This works well until I need to override an atribute on a sub class,...
murphy.tim's user avatar
18 votes
1 answer
8k views

getattr() versus __dict__ lookup, which is faster?

I can dynamically look up object attribute values using object.__dict__[some_key] or getattr(object, some_key). Which is faster or better, and why? >>> class SomeObject: ... pass ... >...
Cole's user avatar
  • 2,509
18 votes
3 answers
7k views

__getattr__ equivalent for methods

When an attribute is not found object.__getattr__ is called. Is there an equivalent way to intercept undefined methods?
hoju's user avatar
  • 29.1k
17 votes
3 answers
2k views

What are the names of the magic methods for the operators "is" and "in"?

I would like to make bool binary operations using the magic methods for these operators. For example, I can get a < b as getattr(a, '__lt__')(b) or a == b as getattr(a, '__eq__')(b). Can I get a ...
nik's user avatar
  • 355
16 votes
2 answers
9k views

How are arguments passed to a function through __getattr__

Consider the following code example (python 2.7): class Parent: def __init__(self, child): self.child = child def __getattr__(self, attr): print("Calling __getattr__: "+attr) ...
Alex's user avatar
  • 43.3k
15 votes
2 answers
9k views

assign a attribute using getattr

I try to assign value to attributes of some calss like the following: for name in dir(modelType): if request.get(name): getattr(model, name) = request.get(name) but get the ...
Alon Gutman's user avatar
15 votes
5 answers
8k views

Get nested attribute from a python object

I have an object with nested attributes like so: obj: attr_1: attr_2 When both attr_1 and attr_2 exists, I can get it like so: obj.attr_1.attr_2 But what if I'm not sure if either ...
Nikita Vstovsky's user avatar
15 votes
4 answers
751 views

Python: inconsistence in the way you define the function __setattr__?

Consider this code: class Foo1(dict): def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value class Foo2(dict): __getattr__ = dict.__getitem__ ...
Albert's user avatar
  • 66.7k
15 votes
1 answer
2k views

Overriding __getattr__ to support dynamic nested attributes

What is the best approach to take if you want to dynamically create and reference nested attributes? I was writing a simple Flickr client, and wanted to match the documented API as closely as ...
Zach Kelling's user avatar
  • 53.3k
14 votes
4 answers
13k views

Using __getattribute__ or __getattr__ to call methods in Python

I am trying to create a subclass which acts as a list of custom classes. However, I want the list to inherit the methods and attributes of the parent class and return a sum of the quantities of each ...
AJ Medford's user avatar
14 votes
3 answers
3k views

Determine if __getattr__ is method or attribute call

Is there any way to determine the difference between a method and an attribute call using __getattr__? I.e. in: class Bar(object): def __getattr__(self, name): if THIS_IS_A_METHOD_CALL: ...
Robin Orheden's user avatar
13 votes
2 answers
2k views

python: cooperative supercall of __getattr__

I'm working with somethign similar to this code: class BaseClass(object): def __getattr__(self, attr): return lambda:'1' class SubClass(BaseClass): def foo(self): suffix = '2'...
bukzor's user avatar
  • 38k
13 votes
0 answers
3k views

How to type-hint return type of __getattr__ method?

I am curious if there is a way in Python 3 to type hint the return type of __getattr__() method in Python. I have the following dummy code I was using for test purposes: class MyClass: def ...
Ritvik The God's user avatar
12 votes
3 answers
4k views

Why doesn't Python have a hybrid getattr + __getitem__ built in?

I have methods that accept dicts or other objects and the names of "fields" to fetch from those objects. If the object is a dict then the method uses __getitem__ to retrieve the named key, or else it ...
Kirk Strauser's user avatar
12 votes
1 answer
5k views

Can the usage of `setattr` (and `getattr`) be considered as bad practice?

setattr and getattr kind of got into my style of programing (mainly scientific stuff, my knowledge about python is self taught). Considering that exec and eval inherit a potential danger since in some ...
Timm Clarsson's user avatar
12 votes
3 answers
7k views

How to intercept instance method calls?

I am looking for a way to intercept instance method calls in class MyWrapper below: class SomeClass1: def a1(self): self.internal_z() return "a1" def a2(self): return ...
Vikas Vikas's user avatar
11 votes
2 answers
4k views

Python Chain getattr as a string

import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in ...
Hellnar's user avatar
  • 63.5k
11 votes
2 answers
9k views

Is it bad practice to use python's getattr extensively?

I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that ...
Wilduck's user avatar
  • 14k
11 votes
2 answers
7k views

How to get foreign key values with getattr from models

I have a model Project and i am getting the attributes of that with the following instr attr = getattr(project, 'id', None) project is the instance, id is the field and None is the default return ...
A.J.'s user avatar
  • 8,777
11 votes
1 answer
2k views

What is the difference between type.__getattribute__ and object.__getattribute__?

Given: In [37]: class A: ....: f = 1 ....: In [38]: class B(A): ....: pass ....: In [39]: getattr(B, 'f') Out[39]: 1 Okay, that either calls super or crawls the mro? In [40]: ...
Neil G's user avatar
  • 32.6k
11 votes
1 answer
13k views

Why is getattr() so much slower than self.__dict__.get()?

The example below is from a REST database driver on Python 2.7. In the __setattr__ method below, if I use the commented out getattr() line, it reduces the object instantiation performance from 600 ...
espeed's user avatar
  • 4,774
10 votes
3 answers
4k views

RecursionError when python copy.deepcopy

I have a problem in python. I have a class whis custom __getattr__ class ChoiceNumToName(object): def __init__(self, django_choice_tuple): self.ods_choice_tuple = django_choice_tuple ...
fuxiuyin's user avatar
  • 151
9 votes
3 answers
23k views

Accessing list items with getattr/setattr in Python

Trying to access/assign items in a list with getattr and setattr funcions in Python. Unfortunately there seems to be no way of passing the place in the list index along with the list name. Here's some ...
insomniaccanuck's user avatar
9 votes
2 answers
8k views

setattr and getattr with methods

I have a boiler platey class that delegates some actions to a reference class. It looks like this: class MyClass(): def __init__(self, someClass): self.refClass = someClass ...
zapatilla's user avatar
  • 1,813
9 votes
2 answers
6k views

Why can't I use __getattr__ with Django models?

I've seen examples online of people using __getattr__ with Django models, but whenever I try I get errors. (Django 1.2.3) I don't have any problems when I am using __getattr__ on normal objects. For ...
Joshmaker's user avatar
  • 4,208
9 votes
2 answers
3k views

How to prevent hasattr from retrieving the attribute value itself

I have a class that implements virtual attributes using __getattr__. The attributes can be expensive, e.g. performing a query. Now, I am using a library which checks if my object has the attribute ...
koriander's user avatar
  • 3,180
8 votes
3 answers
5k views

C++ equivalent of Python getattr

In python, there is a function called getattr which would look like this: class MyObject(): def __init__(self): self.xyz = 4 obj = MyObject() getattr(obj, 'xyz') where the call to ...
ulu5's user avatar
  • 437
8 votes
1 answer
4k views

Python 2 __getattr__ max recursion depth

for example i use this code: class A(object): def __init__(self): self.dict1 = { 'A': 3, 'B': self.A} def __getattr__(self, key): if key in self.dict1: ...
M1k3's user avatar
  • 89
8 votes
1 answer
4k views

Querying for entities with missing properties in app engine Datastore?

I have a model which looks like this: class Example (db.Model) : row_num = db.IntegerProperty(required=True) updated = db.IntegerProperty() ... ... Now when i store values, I may not fill the ...
demos's user avatar
  • 2,630
8 votes
3 answers
1k views

Asymmetric behavior for __getattr__, newstyle vs oldstyle classes

this is the first time I write here, sorry if the message is unfocuessed or too long. I was interested in understanding more about how objects'attributes are fetched when needed. So I read the ...
Filippo's user avatar
  • 81
7 votes
2 answers
18k views

Why is getattr() throwing an exception when an attribute doesn't exist?

This one has me baffled. Consider the following Django models - representing zookeepers and the cages at the zoo that they are responsible for cleaning: class Zookeeper(moodels.Model): name = ...
Nathan Osman's user avatar
  • 72.3k
7 votes
2 answers
2k views

PHP equivalent of send and getattr?

If Ruby gets invited to a party and brings: foobarobject.send('foomethod') .. and Python gets invited to the same party and brings: getattr(foobarobject, 'foomethod')() .. what does PHP have to ...
dreftymac's user avatar
  • 31.9k
7 votes
1 answer
1k views

python getattr built-in method executes default arguments

I dont know if this is something an expected behavior of getattr built_in method. getattr executes the default(3rd) argument as well even if the actual argument(2nd) satisfies the condition. Example: ...
MaNKuR's user avatar
  • 2,628
7 votes
2 answers
3k views

Is there any way to override the double-underscore (magic) methods of arbitrary objects in Python?

I want to write a wrapper class which takes a value and behaves just like it except for adding a 'reason' attribute. I had something like this in mind: class ExplainedValue(object): def __init__(...
Claudiu's user avatar
  • 227k

1
2 3 4 5
8