Questions tagged [hasattr]

38 questions
97
votes
13 answers

hasattr() vs try-except block to deal with non-existent attributes

if hasattr(obj, 'attribute'): # do somthing vs try: # access obj.attribute except AttributeError, e: # deal with AttributeError Which should be preferred and why?
Imran
  • 87,203
  • 23
  • 98
  • 131
39
votes
6 answers

Python's hasattr on list values of dictionaries always returns false?

I have a dictionary that sometimes receives calls for non-existent keys, so I try and use hasattr and getattr to handle these cases: key_string = 'foo' print "current info:", info print hasattr(info, key_string) print getattr(info, key_string,…
Chris Keele
  • 3,364
  • 3
  • 30
  • 52
27
votes
5 answers

Checking for member existence in Python

I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this: class Foo(object): @classmethod def singleton(self): if not…
PierreBdR
  • 42,120
  • 10
  • 46
  • 62
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
6
votes
1 answer

Python's hasattr sometimes returns incorrect results

Why does hasattr say that the instance doesn't have a foo attribute? >>> class A(object): ... @property ... def foo(self): ... ErrorErrorError ... >>> a = A() >>> hasattr(a, 'foo') False I expected: >>> hasattr(a, 'foo') NameError:…
wim
  • 338,267
  • 99
  • 616
  • 750
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
5
votes
3 answers

hasattr on class names

hasattr documentation says that it takes an object and an attribute name and lets you know if that attribute exists on that object. I have discovered that it seems to work on class names too (i.e. not an instance object). Something like: class A: …
5
votes
6 answers

Check multiples hasattr in the same condition

if hasattr(form, 'name') and hasattr(form, 'date'): print(form.name) #'Some name' - True print(form.date) #none - False This condition validates as True even if the hasattr(form, 'date') is false. What is the correct way to validate multiples…
user2983258
  • 151
  • 1
  • 3
  • 9
3
votes
2 answers

How to test if python class parent has method defined?

I have a subclass that may have a method 'method_x' defined. I want to know if 'method_x' was defined somewhere else up the class hierarchy. If I do: hasattr(self, 'method_x') I'll get a truth value that also looks at any methods defined for the…
piRSquared
  • 285,575
  • 57
  • 475
  • 624
3
votes
2 answers

hasattr keeps returning False

class Avatar: def __init__(self, HP=100, damage=10, defends=10, magic=5): self.__hp = HP self.__dam = damage self.__def = defends self.__mag = magic def check_hasattr(self): print…
3
votes
2 answers

Is there a function in python that returns true if all members of an iterable are true?

I'm tryng to learn different ways to do simple things in python, while also learning a bit about some functional practices. I have some numbers that the user inputs, and I want to know if they really are numbers. I've come up with this kind of…
ferhtgoldaraz
  • 1,693
  • 3
  • 15
  • 20
2
votes
2 answers

How detect hashable types with structural pattern matching?

Using structural pattern matching, how do you write a case that matches instances of hashable types? I've tried: for obj in [], (), set(), frozenset(), 10, None, dict(): match obj: case object(__hash__=_): print('Hashable…
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
2
votes
2 answers

How to filter an array of objects on nested attribute using lambda and hasattr?

I have the following Python code: myArray = [{ "id": 1, "desc": "foo", "specs": { "width": 1, "height": 1}}, { "id": 2, "desc": "bar", "specs": { "width": 2, "height": 2, "color": "black"}}, { "id": 3, "desc": "foobar"}] print…
smartmouse
  • 13,912
  • 34
  • 100
  • 166
2
votes
1 answer

Python 3 - Check class attribute without calling __getattr__

TL;DR: Are there alternatives to hasattr which don't trigger property getters? I'm writing a Python interface to some existing code where I am getting and setting values for various shape and section classes. Due to a large number of possible…
Tim Jim
  • 620
  • 5
  • 19
2
votes
2 answers

Detect if a __getattribute__ call was due to hasattr

I'm re-implementing __getattribute__ for a class. I want to notice any incorrect (meaning failures are expected, of course) failures of providing attributes (because the __getattribute__ implementation turned out quite complex). For that I log a…
NirIzr
  • 3,131
  • 2
  • 30
  • 49
1
2 3