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
7
votes
0 answers

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 __getattr__(self, item: str) -> str: return…
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
7
votes
1 answer

Trying to understand __init__.py combined with getattr

I am trying to understand a piece of Python code. First, I have the following file structure: folder1-- model __init__.py file1.py file2.py __init__.py The __init__.py in the folder folder1 has nothing. The __init__.py in the…
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
7
votes
1 answer

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: def func(): print('In Function') class A: …
MaNKuR
  • 2,578
  • 1
  • 19
  • 31
7
votes
1 answer

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: return self.dict1[key] a = A() and…
M1k3
  • 79
  • 1
  • 3
7
votes
1 answer

Why magic methods are not intercepted by __getattr__ implementation in python?

Subj. Example: MyList(object): def __init__(self, list_to_be_wrapped): self._items = list_to_be_wrapped def __getattr__(self, item): return getattr(self._items, item) Then MyList([1, 2, 3])[-1] will raise: …
yashaka
  • 826
  • 1
  • 9
  • 20
7
votes
2 answers

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 = models.CharField(max_length=40) class…
Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
7
votes
2 answers

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__(self, value, reason): self.value = value …
Claudiu
  • 224,032
  • 165
  • 485
  • 680
6
votes
2 answers

doc for __getattr__ defined attributes

I have to customize __getattr__ to call another function to read. This works well except the help(object.attr) does not work. This code is used in an interactive environment, so the help() becomes important to us. Is there a better design to achieve…
Forest Yang
  • 179
  • 5
6
votes
4 answers

Dynamically get dict elements via getattr?

I want to dynamically query which objects from a class I would like to retrieve. getattr seems like what I want, and it performs fine for top-level objects in the class. However, I'd like to also specify sub-elements. class MyObj(object): def…
user394430
  • 2,805
  • 2
  • 28
  • 27
6
votes
1 answer

how to make classes with __getattr__ pickable

How can I modify the classes below to make them pickeable? This question: How to make a class which has __getattr__ properly pickable? is similar but refer to wrong exception in the use of getattr. This other question seems to provide meaningful…
Pierpaolo
  • 1,721
  • 4
  • 20
  • 34
6
votes
5 answers

Python: Convert string into function name; getattr or equal?

I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py…
TallPaul
  • 1,001
  • 4
  • 10
  • 12
5
votes
3 answers

How can I reach a private variable within the object

I would like to modify an object private variable class Example(): __myTest1 = 1 __myTest2 = 1 def __init__(self): pass def modifyTest(self, name = 'Test1', value): setattr(self, '__my'+name, value); I tried the code…
Mokus
  • 10,174
  • 18
  • 80
  • 122
5
votes
1 answer

Can XML-RPC methods be called by name (as strings) in Python?

In python, calling XML-RPC methods involves invoking methods on a proxy object: from xmlrpclib import ServerProxy print ServerProxy('https://example.com/rpc').api.hello_there('John') In some other languages, like perl, you pass your method name as…
Wedgwood
  • 993
  • 9
  • 10
5
votes
1 answer

How to use __getattr__ to delegate methods to attribute?

I have the following class: class MyInt: def __init__(self, v): if type(v) != int: raise ValueError('value must be an int') self.v = v def __getattr__(self, attr): return getattr(self.v, attr) i =…
Jon McClung
  • 1,619
  • 20
  • 28
5
votes
2 answers

How to robustly check a Python property exists?

Given the following class (with a buggy property) then what is the best foolproof way of checking that the bar property exists? class Foo(object): @property def bar(self): raise AttributeError('unforeseen attribute error!') Both…
101
  • 8,514
  • 6
  • 43
  • 69