share post
Sometimes it’s fun to just nerd out for a moment. Python is one of the most popular scripting languages today and we love it too. That’s one reason why LogicMonitor can execute any script or programming language supported by your environment. That means you can enjoy the latest features of your favorite languages in your favorite monitoring tool (right?). If Python is your vice, give Python 3.7’s Data Classes a try!
Groovy, an extension of Java, and PowerShell are two languages that I believe strongly support OOP in a user-friendly way. They let you quickly manipulate custom objects and report their values. Python, while wildly popular and powerful, lagged a bit behind. To see some past examples, search the internet for “Python print class attributes”. At the time of this article, here are some of the top search results from one of the most popular developer resources, Stack Overflow:
It’s not much better if you try to search the official Python 2.7 documentation for classes. Notice every time their examples print information about the classes they assume you already know exactly what you want to show, or, that you’re willing to spend the time explicitly printing each class attribute?
Based on the search results and answers, as well as my own experiences, I saw two main challenges for working with custom Python objects:
For those who are less script savvy, let’s use an analogy to explain the problem. Let’s picture a Python class object as a physical newspaper full of stories. You’re the one who printed this newspaper. You already know the stories. You carefully placed each paragraph, story, and headline. In previous Python versions, when you handed the newspaper to Python and, as a sanity check, asked it to read you one of the news reports, it made you specify each paragraph you wanted read instead of just giving you the whole story. Cute when your toddler says that; frustrating and concerning when your 30 year old aspiring journalist says that.
In 2017, PEP 557 conceptualized Data Classes, which “exist primarily to store values which are accessible by attribute lookup”, and nearly a year later, the release of Python 3.7.0 officially offered an implementation. Data Classes piggyback off of type hinting (PEP 484) and type annotations (PEP 526), respectively introduced in Python 3.5 and 3.6. When it comes to working with objects, people expect to be able to consistently predict data types. While Python still isn’t a strictly typed language, the combination of type hinting and annotations helps both users and IDEs know what data types to expect when working through a larger codebase.
Another part of maturing is being honest about what you care about and how to spend more time focused on that. It’s possible that it’s just me, but I feel like DataClasses were undersold, or, someone really enjoys dealing with tedious processes. Exact words from PEP 557 regarding the Data Class are “[…]there’s really nothing special about the class: the decorator adds generated methods to the class and returns the same class it was given. […] Data Classes save you from writing and maintaining these methods.”.
What are these “generated methods”? Fortunately the abstract of PEP 557 gives an example. Let’s say you had a Python class defined as follows:
@dataclass class InventoryItem: '''Class for keeping track of an item in inventory.''' name: str unit_price: float quantity_on_hand: int = 0 def total_cost(self) -> float: return self.unit_price * self.quantity_on_hand
The Data Class decorator (“@dataclass”), therefore, would automatically generate the following code for you:
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0) -> None: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand def __repr__(self): return f'InventoryItem(name={self.name!r}, unit_price={self.unit_price!r}, quantity_on_hand={self.quantity_on_hand!r})' def __eq__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) == (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented def __ne__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) != (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented def __lt__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) < (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented def __le__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) <= (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented def __gt__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) > (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented def __ge__(self, other): if other.__class__ is self.__class__: return (self.name, self.unit_price, self.quantity_on_hand) >= (other.name, other.unit_price, other.quantity_on_hand) return NotImplemented
Those thirty lines of automatically generated code were for only three attributes: name, unit_price, and quantity_on_hand. The reason why I believe this is significantly undersold is because the level of effort to create and maintain those methods yourself becomes incredibly cumbersome as you add more class attributes. Who feels like dealing with that? Well, maybe Python contributor Eric V. Smith does but partially thanks to him, you don’t have to!
We can see a number of Data Class benefits based on the information we have thus far:
print some_variable
Per PEP 557, Data Classes are not meant to be a full replacement of any other Python library. Furthermore, the PEP article states that Data Classes are not appropriate where:
Python Data Classes combine existing Python features into a concise, declarative syntax in order to bring users an improved experience when managing classes used primarily for data storage. One of the key benefits of Python Data Classes is that you can quickly print string representations of classes and their attributes. Because of LogicMonitor’s powerful extensibility, you can leverage Python Data Classes among all the other newest Python features in your monitoring and portal administration.
Jeoffri enjoys serving LogicMonitor-sponsored scripting meals that are proudly low-calorie, diverse, vegan, innovative, free-range, local, and BPA-free. As far as he knows, none of the code confections have been solar powered but he still joins his colleagues in demonstrating how much he cares about the environment. You can often find Jeoffri in the common area of LM’s Austin WeWork Shazaming a song that’s probably stacked with 7th chords, walking boxes around Austin parking lots, training his dogs on loose leash walking, or buying another lavender plant because he failed to keep the last one alive. Subscribe to our LogicBlog to stay updated on the latest developments from LogicMonitor and get notified about blog posts from our world-class team of IT experts and engineers, as well as our leadership team with in-depth knowledge and decades of collective experience in delivering a product IT professionals love.
LogicMonitor announced the appointment of Nitin Navare as Chief Technology Officer (CTO).
There are a few Agile certifications available to choose from, and in this article, we’ll discuss the best agile certifications currently available for IT professionals.
Join LogicMonitor Wednesday June 1st for Dinner @ Frankie & Johnnie's Steakhouse