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
4
votes
1 answer

Get class object from string

I'm writing the following to generate URLs for my urls.py: urls = { 'overview': { r'^$': [ 'Index' ], r'^/account$': [ 'Account' ], }, 'content': { r'^/content$': [ 'Index' ] …
user2501886
4
votes
3 answers

Obtaining object reference for a method using getattr

Say, I have the following class called Test with a method called start >>> class Test: ... def __init__(self, *args, **kwargs): ... pass ... def start(self): ... pass ... Now, I have a standalone independent function…
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
3
votes
3 answers

Is there a way to inspect incoming args from within __getattr__ or to somehow otherwise redirect a call based upon incoming arguments?

Some background: We have a system for transactions where we devide the flow based upon the country the transaction bills to. We have a logging table that exists in 2 instances, one DB logging transactions to the EU, the other to anywhere else. We…
Silas Ray
  • 25,682
  • 5
  • 48
  • 63
3
votes
2 answers

Python - getattr and concatenation

So in playing around with getattr in my code I discovered the following: myVariable = foo.A.bar works...but something like this: B = "A" myVariable = getattr(foo, B + ".bar") returns an error that foo does not contain an attribute A.bar. Where…
MattyZ
  • 1,541
  • 4
  • 24
  • 41
3
votes
1 answer

Python __getattr__ 'NoneType' object is not callable

For the class Thing, when I call an undefined method such as .doamethod()... class Thing: def __init__(self): pass def __getattr__(self, method): print('Run method: '+method) t = Thing() t.doamethod() ...I get this…
3
votes
1 answer

Python __getattr__ executed multiple times

I've been trying to implement the __getattr__ function as in the following example: PEP 562 -- Module __getattr__ and __dir__ And I don't get why this simple piece of code: # lib.py def __getattr__(name): print(name) # main.py from lib import…
Julien
  • 87
  • 9
3
votes
1 answer

__getattr__ and __getattribute__ for class/static atributes of dynamically generated classes

This question answers how to implement __getattr__ for static/class attributes - using a metaclass. However, I would like to implement __getattr__ and __getattribute__ for a class generated by type() and to make things even more interesting, the…
karlosss
  • 2,816
  • 7
  • 26
  • 42
3
votes
2 answers

can you use getattr to call a function within your scope?

I'm trying to do something like this, but I can't figure out how to call the function bar. def foo(): def bar(baz): print('used getattr to call', baz) getattr(bar, __call__())('bar') foo() Notice, that this is somewhat unusual.…
MetaStack
  • 3,266
  • 4
  • 30
  • 67
3
votes
1 answer

getattr - Exception Value: module 'django.db.models' has no attribute 'model_name''

I have a probleme for use a variable in model name, i want to take this command : MyVar.objects.all().delete() and in the same way i have to a probleme for take this : class MyCsvModel(CsvDbModel): class Meta: dbModel =…
oz grow
  • 55
  • 10
3
votes
5 answers

__getattr__ returning lambda function requiring one argument does not work

I am in the process of learning Python 3 and just ran into the getattr function. From what I can tell, it is invoked when the attribute call is not found in the class definition as a function or a variable. In order to understand the behaviour, I…
chrillof
  • 325
  • 2
  • 15
3
votes
3 answers

Python recursively __getattribute__

I need to implement such behavior: obj.attr1.attr2.attr3 --> obj.attr1__attr2__attr3 It looks like I have to override obj's class __getattribute__ and also use python descriptors somehow. UPDATE: I have a django project. obj is django-haystack's…
Roman Dolgiy
  • 1,521
  • 1
  • 15
  • 21
3
votes
2 answers

How to get instance attribute inside magic __getattr__?

In a class I want to map call to inst.addr to a value crated by calling inst.addr_fun(), and thus created this code: class Common: ... def __getattr__(self, name): if hasattr(self, '{}_fun'.format(name)): return…
EquipDev
  • 5,573
  • 10
  • 37
  • 63
3
votes
2 answers

__getattr__ throwing maximum recursion error when __setattr__ implemented

I'm trying to create a circle class using the magic methods __getattr__ and __setattr__, and I seem to have my __getattr__ working, but when I implement __setattr__ (which should only allow the values for x and y to be set if the value is an int,…
BrxttB
  • 103
  • 1
  • 9
3
votes
1 answer

Overriding __getattr__ method for one instance of a class?

I'm working on a project right now that deals with functions in an abstract mathematical sense. Without boring the reader with the details, I'll say that I had the following structure in an earlier version: class Foo(Bar): def __init__(self, a,…
David Legg
  • 271
  • 1
  • 4
  • 12
3
votes
2 answers

python calling classes dynamically

I want to call python classes dynamically, These are the classes that I want to call class AutosoukModelMakeFuzzyComparisonModule: def __init__(self,configurationLoader=None, moduleConfigurationFile=None, settings=None): pass and…
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253