Python Built-in Functions

Python is the language of this decade. This popularity is not an accident. There is a reason for its popularity. Inspite of being an interpreted, scripting language, Python has a lot of application in domains that require extreme performance. One of the primary reasons for the power of Python is its treasure of built in functions.

Most Python code eventually invokes these functions - that are implemented in a low level language like C. These functions are thoroughly optimized in every way, to enable extreme performance. This helps us derive the convenience of a scripting language, with the performance near to that of a low level language.

Let's have a look at the major Built in Functions from AWS. Below, I have grouped them based on the area of functionality.

Numbers & Text

These are the most basic set of functions - that help us with manipulation of basic data types of text and numbers. They are used to modify or combine the data or to transform its type. These functions do not alter the data in place. They just return the transformed value.

abs(x)Return the absolute value of a number.
round(x [,n])Return number rounded to n digits precision after the decimal point.
eval("expression" [, globals[, locals]])This can evaluate the string expression. For example expression could be "1 + x". It will return the output based on the value of x in that context. We can override the global and local context of this expression by providing additional parameters - maps that can override the global and local variables in context.
divmod(a, b)For integer a, b - this returns a pair of number (a//b, a%b). But this function also works for floating point numbers. In that case, we have two integers m,n such that m*b + n = a
pow(base, exp [,mod])As the name suggests, this returns base^exp. When we provide the additional third argument, we get base^exp % mod. The first two parameters could be integers of floats. But the third parameter is allowed only if all arguments are integers.
bin(n)Convert an integer number to a binary string prefixed with "0b"
bool(x)Returns a boolean True or False, based on the "Truth Test" of the variable x. (False, 0, "", null, empty collections are False, others are True)
chr(n)Return the string representing a character whose Unicode code point is the integer n.
float(x)Return a floating point number constructed from a number or string x.
hex(x)Convert an integer number to a lowercase hexadecimal string prefixed with “0x”
int(x)Return an integer object constructed from a number or string x, or return 0 if no arguments are given.
oct(x)Convert an integer number to an octal string prefixed with “0o”
ord('c')Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
complex(r [,i])Returns a complex number with the given real and immaginary parts.
format(value[, spec])As the name suggests, this generates a formatted string out for the given data

Collections & Iterables

The next set of functions help us around with the collections and iterators. Python provides interesting ways to iterate through and work with collections and iterators. Let's look at some of them

But, before we jump in, it is important that we understand an important concept. What is an iterable? An iterable is different from a collection. Collections in Python are iterable. But all iterables are not collections. Iterable is a lot broader - something that we can iterate. In specific syntax, iterable is a python object that allows you to fetch the "current" and the "next" value; and lets you progress to the next value such that the next becomes the current.

The names of these functions are quite intuitive and so we do not need any particular explanation of what it does. Just listing them is enough.

  • Python provides for four types of collections out of the box: tuple, list, frozenset, set and dictionary. We have four corresponding methods that build a tuple, list, set or a dictionary out of the given data. Their names are quite intuitive: tuple(), list(), frozenset(), set() and dict().
  • There are some functions that extract a single value out of the entire data of the iterable. For example, max(), min(), sum(), len(). Their names are intuitive and we need not go deeper into what they do.
  • Next, we have some that work on each element of the iterable and return the result. For example, all(), any(), filter()
  • Then we have a set of functions that can help us generate iterators and collections out of the available data. range(), iter(), enumerate(), bytearray(), next()
  • And finally, we have some functions that return a new iterable or collection - that is a modified form of the input collection or iterable. slice(), sorted(), zip(), map(), reversed()

Objects & Code

Python is a perfect Object Oriented Language. It allows functional programming, but it is object oriented in its core. In Python, everything is an Object. Including the source code itself. The Object itself is an Object that can be viewed and altered - using some of the built in functions. Let us see how.

Object Representation

The first four methods help represent the object in various forms

id(object)Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. In Cython - the most common implementation of Python, this refers to the memory location of the object.
str(object)Generates a string representation of the object. This may or may not be a unique representation of the object or its contents. That depends upon how the class implements it.
repr(object)This return a string containing a printable representation of an object. For many types, this function returns return a string that yields an object with the same value when passed to eval(). There are some others that return a string enclosed in angle brackets, containing the name of the object type - together with additional information - like the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
ascii(object)This creates an ASCII representation of the object - similar to that generated by repr(). But, here, we are assured of ASCII characters. Any non-ASCII characters in repr() are appropriately represented using the correct escape sequence.
hash(object)This returns the hash value of the object. Hash values are simple integers, and easy to compute. Mathematically, we can have have different objects giving the same hash. But that scenario is rare. If we want to compare two objects, computationally it is often much easier to compare the hash values first, and then go for comparing the objects - only if the hash values are equal.
memoryview(object)Return a "memory view" object created from the given argument. With this, we can refer to the raw binary data beneath the object

Object Attributes

Python provides functions that can allow us to directly access the attributes of any given object. Without looking for its type or hierarchy, we can just peep into the object and even modify its content and structure. This is a very powerful tool - to be used with care.

dir([object])This lists all the attributes of the given object - that is - list of all the variables, constants, functions, class specifications, etc defined within the namespace of the object. If no parameter is provided, it gives the list of all variables in the global name space.
delattr(object, attribute)This deletes the attribute from the given object.
setattr(object, attribute, value)As one would expect, this sets an attribute for the object.
getattr(object, attribute)This returns the value of the particular attribute from the object.
hasattr(object, name)Check if there is an attribute of the specified name in the given object.
vars(object)Returns the dictionary of all the variables defined in the object. Unlike the dir(), this returns only the object level variables.
locals()Returns the dictionary of all the local variables in current scope
globals()Returns the dictionary of all the local variables in current scope

Object Hierarchy

Next, we have methods that can work with the Object hierarchy. Let us look at each of them.

object()This return a new empty object. This object is a base for all classes. It has the core methods that are common to all instances of Python classes. This function does not accept any arguments.
isinstance(object, classinfo)Returns true or false - if the given object is an instance of the class. That could be a direct instance, or an instance of another class in its subclass hierarchy.
issubclass(class, classinfo)Returns true or false - if the class is a subclass of classinfo.
callable(object)Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

And there are other functions that provide an elaborate functionality, hence deserve a fresh section.


Anyone who has worked on developing an object oriented design, understands the evils of directly accessing an object attribute. It is always advisable that we use getter/setter methods for that. But, we all know the convenience and temptation of using the attributes directly.

Python is built for easy development and maintenance. Hence, it provides for both. This is done using the concept of an object property. Check out the code below:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "Initial value of the property 'x'.")

Here, _x is the private attribute that is accessed as property x, using the four methods. If object o is an instance of the class C, then

y = o.x   # Invokes the getx
o.x = y   # invokes the setx

We can also use property as a decorator for a method:

class C:
    def __init__(self):
        self._x = None

    def x(self):
        """I'm the 'x' property."""
        return self._x

    def x(self, value):
        self._x = value

    def x(self):
        del self._x

Note that the name of each method is x.


In Python, the Type of an object is an object too. We can query it from the object, or we can create a new Type using the type function. Thus, the type function can be invoked in two different contexts - with a single argument, to query the type of the parameter object. And with three arguments, to define a new Type.

Let's check how

# Check the type of an object.
>>> a = {}
>>> type(a)
<class 'dict'>

And we can also create a new Type

>>> class T1:
...   a = 1

>>> T2 = type('T2', (object,), dict(a=1))

>>> o1 = T1()
>>> type(o1)
<class '__main__.T1'>

>>> o2 = T2()
>>> type(o2)
<class '__main__.T2'>

In the above code, we create two classes T1 and T2 - one using the simple class syntax, and the other using the type function. Both do the same job.