Python: access structure field through its name in a string

Ricky Robinson picture Ricky Robinson · Apr 17, 2013 · Viewed 10.9k times · Source

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

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

Normally I would do it individually:

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

Is there any way to access those packet fields from a list of strings including what each one of them is called? Like:

for field in fieldsToCompare:
    if a[IP].field == b[IP].field:
         ... do stuff...

Answer

Gareth Webber picture Gareth Webber · Apr 17, 2013

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

getattr(x, 'foobar')
x.foobar

setattr() is its counterpart.