Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

First-Class Objects

All objects in Python are said to be “first class.” This means that all objects that can be named by an identifier have equal status. It also means that all objects that can be named can be treated as data. For example, here is a simple dictionary containing two values:

items = {
    'number' : 42
    'text' : "Hello World"
}

The first-class nature of objects can be seen by adding some more unusual items to this dictionary. Here are some examples:

items["func"]  = abs            # Add the abs() function
import math
items["mod"]   = math           # Add a module
items["error"] = ValueError     # Add an exception type
nums = [1,2,3,4]
items["append"] = nums.append   # Add a method of another object

In this example, the items dictionary contains a function, a module, an exception, and a method of another object. If you want, you can use dictionary lookups on items in place of the original names and the code will still work. For example:

>>> items["func"](-45)         # Executes abs(-45)
45
>>> items["mod"].sqrt(4)       # Executes math.sqrt(4)
2.0
>>> try:
...    x = int("a lot")
... except items["error"] as e:   # Same as except ValueError as e
...     print("Couldn't convert")
...
Couldn't convert
>>> items["append"](100)       # Executes nums.append(100)
>>> nums
[1, 2, 3, 4, 100]
>>>

The fact that everything in Python is first-class is often not fully appreciated by new programmers. However, it can be used to write very compact and flexible code. For example, suppose you had a line of text such as "GOOG,100,490.10" and you wanted to convert it into a list of fields with appropriate type-conversion. Here’s a clever way that you might do it by creating a list of types (which are first-class objects) and executing a few simple list processing operations:

>>> line = "GOOG,100,490.10"
>>> field_types = [str, int, float]
>>> raw_fields = line.split(',')
>>> fields = [ty(val) for ty,val in zip(field_types,raw_fields)]
>>> fields
['GOOG', 100, 490.10000000000002]
>>>
  • + Share This
  • 🔖 Save To Your Account