Questions tagged [getattr]

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

The function's schematics are as follows:

getattr(object:object, name:str[, default:object]) -> value

where object is the object, name is the named attribute, and default, if supplied, is the default value to return if the attribute can not be found. If default is not supplied and the object can not be found, an AttributeError is thrown.

Below is a demonstration of the function's features:

>>> class Test:
...     def __init__(self):
...         self.attr = 1
...
>>> myTest = Test()
>>> getattr(myTest, 'attr')
1
>>> getattr(myTest, 'attr2', 'No attribute by that name')
'No attribute by that name'
>>> getattr(myTest, 'attr2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Test instance has no attribute 'attr2'
>>>
378 questions
11
votes
1 answer

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 rps to 230. Why is getattr() so much slower than…
espeed
  • 4,754
  • 2
  • 39
  • 51
11
votes
2 answers

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 splitted_attrs: current_dom = getattr(current_dom,…
Hellnar
  • 62,315
  • 79
  • 204
  • 279
11
votes
2 answers

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 type. My question is: what if I want to get the…
A.J.
  • 8,557
  • 11
  • 61
  • 89
11
votes
1 answer

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 told). Considering that exec and eval inherit a potential danger since in some cases they might lead to security issues, I was…
Timm Clarsson
  • 111
  • 1
  • 4
10
votes
3 answers

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 self.choice_data = {} …
fuxiuyin
  • 151
  • 1
  • 10
10
votes
2 answers

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 functions are first class objects in python. For…
Wilduck
  • 13,822
  • 10
  • 58
  • 90
10
votes
1 answer

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]: getattr(A, 'f') Out[40]: 1 This is expected. In…
Neil G
  • 32,138
  • 39
  • 156
  • 257
9
votes
3 answers

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 of my tries with some example code: class Lists…
insomniaccanuck
  • 91
  • 1
  • 1
  • 2
9
votes
2 answers

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 example: class Post(object): def…
Joshmaker
  • 4,068
  • 3
  • 27
  • 29
9
votes
2 answers

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 def action1(self): …
zapatilla
  • 1,711
  • 3
  • 22
  • 38
9
votes
2 answers

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 before actually getting it. As a consequence, a…
koriander
  • 3,110
  • 2
  • 15
  • 23
8
votes
3 answers

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 Python 2.7 documentation titled "Data Model" here, I…
Filippo
  • 81
  • 2
8
votes
1 answer

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 value for the updated property every time, which…
demos
  • 2,630
  • 11
  • 35
  • 51
8
votes
3 answers

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 getattr would return 4. Is there a similar way to do…
ulu5
  • 439
  • 7
  • 11
7
votes
2 answers

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 bring to the party? Bonus question: If Ruby and…
dreftymac
  • 31,404
  • 26
  • 119
  • 182
1 2
3
25 26