We saw in the earlier post what is auto-vivification and how we can implement it in JavaScript. Can we do it in Python as well? Yes, Sure.
Python does not have built in auto-vivification
Let's see if it supports it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Nope! So what can we do? Well, Python is a dynamic language, which allows us not only to add properties (attributes) at runtime but we can also ‘intercept’ calls to attributes which do not exist.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
So, can we intercept univ.college access and do something different? Sure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Great, we can intercept calls for missing attributes, but can we create the attribute on the fly? Sure
Magic of dunders ( double underscores) Here we override __getattr__/__setattr__ for univ.college.stream.year = “A+” and we override __getitem__ for univ[‘college’][‘stream’][‘year’] = “A+”
auto inherits a dictionary
This way we can store the attributes in “dict” we are inheriting which simplifies our code to bare minimum. We can also show “bravado” and build this WITHOUT inheriting from dict and manage everything ourselves. Perhaps, another blog post?
Over to final code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters