5
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 hasattr?

user2983258
  • 151
  • 1
  • 3
  • 9
  • 1
    Note that `hasattr` checks purely for existence. If it exists but is falsy it's still true. You may want a form of `getattr` instead - but also double check you don't mean `form.name` instead of just `name`... – Jon Clements Dec 12 '13 at 12:25

6 Answers6

18

You can use all

if all(hasattr(form, attr) for attr in ["name", "date"])
hoefling
  • 59,418
  • 12
  • 147
  • 194
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
2

If you have more than one value to check if it is a truthy attribute of an object, you can do like this

if all(getattr(form, attrib) for attrib in ["name", "date"]):
    ....
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

What you're looking is probably not hasattr, but getattr.

if getattr(form, 'name') and getattr(form, 'date'):

As hasattr will check if form has the attribute name. It will check if form.name exists, not getting the value of form.name. And getattr is there for that!

Hope this helps!

aIKid
  • 26,968
  • 4
  • 39
  • 65
1

Even if the value of the attribute is False, it still has the attribute which is why it is not failing (as you are expecting it to).

hasattr will only check if the attribute exists, not what its value is. You need getattr.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

Try use getattr:

if getattr(form, 'name', None) and getattr(form, 'date', None):
    print(name)
    print(date)

getattr(form, 'name', None) - this None is default value, if not field

crazyzubr
  • 1,072
  • 7
  • 14
0

Your condition is fine. Your use of the variables below probably isn't -- I think you mean to use form.name and form.date.

If you want to check whether they exist and that their value isn't None, try:

if getattr(form, 'name') is not None and getattr(form, 'date') is not None:
    print(form.name)
    print(form.date)
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79