Home > Enterprise >  Check if attribute exists python
Check if attribute exists python

Time:10-25

I have some elements each has some attribute

Example:

a1 = Quadrupole(Name= 'qd1.1', Length = 2.9)

Some of them had additional attribute called R1:

a2 = Quadrupole(Name= 'qd1.1', Length = 2.9, R1=some value)

I want to loop through this element and append the attribute R, first i got the error "'Quadrupole' object has no attribute 'R1'" for the elements that don't have the attribute, i want to append zero value for these elements, i want to implement something like:

i = 0
while (i < len(elements_indexes)):
      if (a[i].FamName).startswith('q') and a[i].R1 exist:
         skew_quad_coof = a[i].R1
      else:
          skew_quad_coof = 0
      k_qs.append(skew_quad_coof)
      i  = 1

However, this did not work

CodePudding user response:

You can use hasattr:

for i in range(len(elements_indexes)):
    if a[i].FamName.startswith('q') and hasattr(a[i], "R1"):
        skew_quad_coof = a[i].R1
    else:
         skew_quad_coof = 0
    k_qs.append(skew_quad_coof)

Or, even better, using a default value of getattr, and rewriting slightly the rest of your function.

for i in range(len(elements_indexes)):
    k_qs.append(
        getattr(a[i], "R1", 0)
        if a[i].FamName.startswith('q')
        else 0
    )

CodePudding user response:

hasattr() could be used to check the existence.

see also: https://stackoverflow.com/a/610893/135699

  • Related