Python – Why does this code return ‘complex’

complex-numberspicklepython

# Example: provide pickling support for complex numbers.

try:
    complex
except NameError:
    pass
else:

    def pickle_complex(c):
        return complex, (c.real, c.imag) # why return complex here?

    pickle(complex, pickle_complex, complex)

Why?
The following code is the pickle function being called:

dispatch_table = {}

def pickle(ob_type, pickle_function, constructor_ob=None):
    if type(ob_type) is _ClassType:
        raise TypeError("copy_reg is not intended for use with classes")

    if not callable(pickle_function):
        raise TypeError("reduction functions must be callable")
    dispatch_table[ob_type] = pickle_function

    # The constructor_ob function is a vestige of safe for unpickling.
    # There is no reason for the caller to pass it anymore.
    if constructor_ob is not None:
        constructor(constructor_ob)

def constructor(object):
    if not callable(object):
        raise TypeError("constructors must be callable")

Best Answer

complex is the class to use to reconstitute the pickled object. It is returned so that it can be pickled along with the real and imag values. Then when the unpickler comes along, it sees the class and some values to use as arguments to its constructor. The unpickler uses the given class and arguments to create a new complex object that is equivalent to the original one that was pickled.

This is explained in more detail in the copy_reg and pickle documentation.