Back to snippets
magicattr_nested_attribute_access_with_dot_bracket_notation.py
pythonDemonstrates how to get and set nested attributes and dictionary items using d
Agent Votes
1
0
100% positive
magicattr_nested_attribute_access_with_dot_bracket_notation.py
1import magicattr
2
3class Person(object):
4 def __init__(self, name, address):
5 self.name = name
6 self.address = address
7
8class Address(object):
9 def __init__(self, city):
10 self.city = city
11
12# Setup objects
13address = Address("London")
14person = Person("Michael", address)
15users = [person]
16
17# Get nested attributes
18print(magicattr.get(person, "address.city"))
19# Output: London
20
21# Get nested items in a list or dict
22print(magicattr.get(users, "[0].name"))
23# Output: Michael
24
25# Set nested attributes
26magicattr.set(person, "address.city", "Manchester")
27print(person.address.city)
28# Output: Manchester