Anonymous Type in Python

Anonymous type is a useful feature in C#. Here is the example from the Microsoft’s site.

var v = new { Amount = 108, Message = "Hello" };
// Rest the mouse pointer over v.Amount and v.Message in the following  
// statement to verify that their inferred types are int and string.  
Console.WriteLine(v.Amount + v.Message);

You don’t have to have a class with bunch of attributes beforehand to create an object. The same kind of technique can be done with Python and I’ve actually used it at work.

class Data(dict):
    __getattr__, __setattr__ = dict.get, dict.__setitem__

if __name__ == '__main__':
    v = Data(Amount=108, Message="Hello")

You do need to prepare a class that inherits from dict but that’s just two lines.

You could have a list of the objects and even sort them. Here is an example.

class Data(dict):
    __getattr__, __setattr__ = dict.get, dict.__setitem__

if __name__ == '__main__':
    records = []
    records.append(Data(Amount=108, Message="a"))
    records.append(Data(Amount=101, Message="b"))
    records.append(Data(Amount=99, Message="c"))
    records.append(Data(Amount=110, Message="d"))
    records.append(Data(Amount=111, Message="e"))
    records.append(Data(Amount=91, Message="c"))

    # Sort by Amount
    records = sorted(records, key=lambda record: record.Amount)

    # Sort by Message
    records = sorted(records, key=lambda record: record.Message)

If you have multiple attribute to sort by, you can list the attributes in a comma delimited way.

Leave a Reply

Your email address will not be published.