Explain Codes LogoExplain Codes Logo

What is & How to use getattr() in Python?

python
getattr
setattr
hasattr
Anton ShumikhinbyAnton Shumikhin·Mar 11, 2025
TLDR

Python's getattr() is a built-in function utilized to access an object's attribute dynamically using its string representation. This function is particularly beneficial when you don't know the attribute name until runtime.

Here's an illustrative example:

class Person: def __init__(self, name): self.name = name person = Person("Bob") attr_name = "name" # Getting attribute value “Bob-style” name = getattr(person, attr_name) print(name) # Prints: Bob

In this case, getattr(person, attr_name) fetches the value of person.name. If the attribute referred to by attr_name doesn't exist, getattr() can be accompanied by a third argument declaring a default return value. This feature helps avoid AttributeError.

A Deep-dive into dynamic attribute access

Dynamic attribute retrieval and safe fallback

getattr() function enables dynamic retrieval of object attributes. It also provides an optional parameter to define a default value whenever the specified attribute is missing, gracefully preventing AttributeError:

default_name = getattr(person, 'age', 'Age Confidential') print(default_name) # Prints: Age Confidential, if person.age doesn't exist # Even Bob’s age is a secret to us.

Executing methods dynamically

When you have a list of method names, and you wish to call them dynamically, getattr() can be your best pal! Here is an example:

methods_to_execute = ['start', 'run', 'finish'] for method_name in methods_to_execute: method = getattr(obj, method_name, None) # Let's call Bob for some action, shall we? if method: method()

Power combo: dir() + getattr()

For effective introspection, combining dir() and getattr() can be quite useful. This combination allows you to loop through all attributes of an object and fetch their values dynamically:

for attr_name in dir(person): attr_value = getattr(person, attr_name) print(f"{attr_name}: {attr_value}") # Bob’s private life won’t be private anymore.

Running conditional code with getattr()

Metaprogramming and URL routing

getattr() facilitates metaprogramming, being pivotal in web development frameworks like Django or Flask to map URLs to callable functions transparently:

def show_blog(request, id): # fetch blog code def show_author(request, id): # fetch author code route_func_map = { 'blog': 'show_blog', 'author': 'show_author' } # Routing like Google maps, but for functions. func_name = route_func_map.get(request.path, None) if func_name: func = getattr(sys.modules[__name__], func_name) func(request, id)

Embracing platform specifics

Connect and organize platform-specific behaviors using getattr(). It helps in maintaining clean and platform-independent code:

class Linux: def reboot(self): # Linux-specific reboot code class Windows: def reboot(self): # Windows-specific reboot code os_type = 'Linux' # Dynamically determined os_instance = getattr(sys.modules[__name__], os_type)() os_instance.reboot() # Dynamically calls Linux.reboot() # Time for a short coffee break while Linux reboots!

Introducing setattr() and hasattr()

Using setattr() to set values

The dynamic attribute counterpart to getattr() is setattr(). Use it to set the value of an attribute at runtime:

for key, value in data_dict.items(): setattr(person, key, value) # Maybe we could change Bob’s age after all.

Cross-checking attribute existence

Before using getattr(), you can ideally check if the attribute exists on an object using hasattr():

if hasattr(person, 'middle_name'): name = getattr(person, 'middle_name', 'Unknown') # Bob could have a fancy middle name, like Maximus or something.