Python: access structure field through its name in a string

In Scapy, I want to compare multiple header fields between any two packages a and b . This list of fields is predefined, say:

 fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header 

I usually did this individually:

 if a[IP].tos == b[IP].tos: ... do stuff... 

Is there a way to access these package fields from a list of strings, including what each of them calls? How:

 for field in fieldsToCompare: if a[IP].field == b[IP].field: ... do stuff... 
+4
source share
2 answers

You can use getattr() . These lines are equivalent:

 getattr(x, 'foobar') x.foobar 

setattr() is a copy of it.

+11
source

I think you are looking for getattr() . Try it ...

 for field in fieldsToCompare: if getattr(a[IP], field) == getattr(b[IP], field): ... do stuff... 
+2
source

All Articles