Explain Codes LogoExplain Codes Logo

Python: access class property from string

python
attribute-access
dynamic-attribute
getattr
Alex KataevbyAlex Kataev·Dec 1, 2024
TLDR

To access a class property using a string name, use Python's built-in getattr function. Here's a quick example:

class MyClass: my_property = "value" # Hey, it's just a simple string! instance = MyClass() value = getattr(instance, 'my_property') print(value) # You've got "value", lucky you!

In this line, getattr(instance, 'property_name'), we're poking around instance to snatch the my_property's value. And voilà! We got "value".

Additionally, you can modify or delete class properties with setattr(instance, 'property_name', new_value) and delattr(instance, 'property_name'), respectively.

Mastering dynamic attribute access

Setting properties: setattr()

In addition to getattr for accessing properties, you can use setattr for setting them dynamically:

setattr(instance, 'my_property', 'new_value') # Abracadabra, and my_property changes!

This command turns the my_property into "new_value", giving us a brilliant display of attribute metamorphosis. Remember though, with great power comes great data integrity responsibility!

Deleting attributes: delattr()

Ever need to bid adieu to a class property? Use delattr:

delattr(instance, 'my_property') # Property, we hardly knew ye.

Abruptly, instance no longer carries my_property, helpful for handling ephemeral or context-sensitive properties.

Unfounded attributes and default values

In cases where getattr can't locate the attribute, it raises an AttributeError. To bypass this hiccup, supply a default value:

default_value = getattr(instance, 'non_existent_property', 'default') # Saved by the default!

If non_existent_property continues to elude us, "default" calmly steps in, providing safe passage through error-prone terrain.

Dictionaries: An alternative attribute container

If dynamic attribute access via getattr isn't sufficient, consider bundling attributes into a dictionary for more structured, string-keyed access:

class MyClass: def __init__(self): self.properties = {'property1': 'value1', 'property2': 'value2'} # Dictionary power! def get_property(self, property_name): return self.properties.get(property_name, 'default_not_found') # Safe and sound. instance = MyClass() print(instance.get_property('property2')) # "value2", found ya!

Here, get_property serves as a safe harbor, returning a default value when the sought property hides.

Broader horizons: Exploring attribute handling

Embracing dictionary-like object access

For a more intuitive workflow, Python allows overloading the __getitem__ method to enable dictionary-like property access:

class MyClass: my_property = "value" # It's secure in its own class. def __getitem__(self, key): return getattr(self, key) # Attribute shopping! instance = MyClass() print(instance['my_property']) # I just got a "value", awesome!

In this setup, we're augmenting our class with a custom __getitem__ method that leverages getattr, offering that sweet, familiar dictionary syntax.

Attribute existence check: hasattr()

To avoid unexpected errors, check attribute existence with hasattr before accessing or setting it:

if hasattr(instance, 'my_property'): value = getattr(instance, 'my_property') # Confirm before you commit!

Alright detectives, this tight pattern ensures no non-existent attribute can surprise us!