Python type() Function

Python’s built-in type() function has two purposes. First, you can pass an object as an argument to check the type of this object. Second, you can pass three arguments—name, bases, and dict—to create a new type object that can be used to create instances of this new type. Usage Learn by example! Here’s an example … Read more

Python object() Function

Python’s built-in object() function takes no argument and returns a new featureless object—the base and parent of all classes. As such it provides all methods that are common to all Python class instances such as __repr__() and other “dunder” methods. However, unlike for all non-object instances, you cannot assign arbitrary attributes to an instance of … Read more

Python repr() Function — A Helpful Guide with Example

Python’s built-in repr(obj) function returns the standard string representation of the provided object. This often includes the type and memory address of the object—for lack of further information. For example, the returned string representation may be ‘<main.Car object at 0x000001F66D11DBE0>’ for a custom object of type Car. The function internally calls the method obj.__repr__() which … Read more

Python str() Function

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion. Syntax str() Syntax: str(object) # –> Most common case: convert an object to a string str(object=b”, encoding=’utf-8′, errors=’strict’) # –> Not so common case: Converts a bytes or … Read more

Python’s __import__() Function — Dynamically Importing a Library By Name

Python’s built-in “dunder” function __import__() allows you to import a library by name. For example, you may want to import a library that was provided as a user input, so you may only have the string name of the library. For example, to import the NumPy library dynamically, you could run __import__(‘numpy’). In this tutorial, … Read more

Python getattr()

Python’s built-in getattr(object, string) function returns the value of the object‘s attribute with name string. If this doesn’t exist, it returns the value provided as an optional third default argument. If that doesn’t exist either, it raises an AttributeError. An example is getattr(porsche, ‘speed’) which is equivalent to porsche.speed. Usage Learn by example! Here’s an … Read more

Python setattr()

Python’s built-in setattr(object, string, value) function takes three arguments: an object, a string, and an arbitrary value. It sets the attribute given by the string on the object to the specified value. After calling the function, there’s a new or updated attribute at the given instance, named and valued as provided in the arguments. For … Read more