Python getattr() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, getattr(obj, "name") does the same as obj.name, but the attribute name is a string that can be decided at runtime. That makes it the tool for dynamic code: choosing a method from user input, a config file, or a loop.

If the attribute does not exist, it raises AttributeError, unless you pass a third argument: getattr(obj, "name", default) returns the default instead. It works on any object, including modules, classes, and strings.

getattr() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass the object, the attribute name, and optionally a default.

python
value = getattr(obj, "name")
value = getattr(obj, "name", default)
CallWhat it does
getattr(user, "name")Same as user.name.
getattr(user, "email", None)None if there is no email attribute.
getattr(obj, op)(a, b)Call a method chosen at runtime.
getattr(math, "pi")Works on modules too.

If the name is fixed in your code, plain dot access (obj.name) is clearer; use getattr() when the name is in a variable.

Library declarations
python
getattr(object, name, /)
getattr(object, name, default, /)

Parameters

ParameterDescription
objectRequired. Any object.
nameRequired. The attribute name as a string.
defaultOptional. Returned instead of raising AttributeError.

Return Value

Return ValueDescription
anyThe attribute value, or default if it is missing.

Python Examples

Example 1 — Read Attributes with a String Name

Read existing attributes, use a variable as the name, and fall back to a default.

python
class User:
    def __init__(self):
        self.name = "Ana"
        self.age = 31


u = User()
print(getattr(u, "name"))
field = "age"
print(getattr(u, field))
print(getattr(u, "email", "not set"))
try:
    getattr(u, "email")
except AttributeError:
    print("no attribute 'email' and no default")

How It Works

  1. Like dot access. getattr(u, "name") returns the same value as u.name.
  2. Name in a variable. field decides at runtime which attribute is read.
  3. Default value. The missing email returns "not set" instead of failing.
  4. No default, error. Without the third argument, a missing attribute raises AttributeError.

Example 2 — Call Methods Chosen at Runtime

Pick calculator methods by name and skip operations that are not defined.

python
class Calculator:
    def add(self, a, b):
        return a + b

    def mul(self, a, b):
        return a * b


calc = Calculator()
for op, a, b in [("add", 2, 3), ("mul", 4, 5), ("pow", 2, 8)]:
    method = getattr(calc, op, None)
    if method is None:
        print(op, "is not supported")
    else:
        print(op, method(a, b))

How It Works

  1. Bound methods. getattr(calc, "add") returns a method already tied to calc.
  2. Call it later. method(a, b) runs it with the loop's numbers.
  3. Safe lookup. The None default marks unsupported operations instead of crashing.
  4. Replaces if/elif chains. New operations only need a new method, not another branch.

Example 3 — Modules, Strings, and Nested Attribute Paths

Use getattr() on a module and a string, then follow a dotted path with functools.reduce.

python
import math
from functools import reduce

print(getattr(math, "sqrt")(16))
print(getattr("hello", "upper")())


class Address:
    city = "Oslo"


class Person:
    address = Address()


path = "address.city"
print(reduce(getattr, path.split("."), Person()))

How It Works

  1. Module functions. getattr(math, "sqrt") fetches the function; the extra parentheses call it.
  2. Methods of values. A string's upper method can be fetched by name too.
  3. Dotted paths. reduce applies getattr step by step: first address, then city.
  4. Any depth. The same line handles paths with more parts, like "a.b.c".

Frequently Asked Questions

It reads an attribute whose name is given as a string: getattr(obj, "x") is obj.x.
Pass a default as the third argument: getattr(obj, "x", None).
getattr(obj, "method_name")(arguments). Use a default or hasattr() if it might be missing.
getattr() returns the value; hasattr() only tells you whether getattr() would succeed.
Not directly. Split the path and apply getattr for each part, for example with functools.reduce.

Next: globals()

Get the dictionary of module-level names.

globals() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful