Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Type-Enforced Data Model | Building Useful Descriptors
Python Descriptors Explained
Section 3. Chapter 4
single

single

Challenge: Type-Enforced Data Model

Swipe to show menu

Task

Swipe to start coding

You are building a reusable validation layer for a financial data model. Your task is to implement a descriptor hierarchy and apply it to two classes.

  1. Implement a base class Validator with:

    • __set_name__(self, owner, name) that stores the attribute name in self._name;
    • __get__(self, obj, objtype=None) that returns self when obj is None, otherwise returns obj.__dict__.get(self._name);
    • __set__(self, obj, value) that calls self.validate(self._name, value) and then stores the value in obj.__dict__[self._name];
    • an abstract validate(self, name, value) method that raises NotImplementedError.
  2. Implement PositiveFloat(Validator) whose validate raises ValueError if value is not a positive int or float.

  3. Implement NonEmptyString(Validator) whose validate raises ValueError if value is not a non-empty string after stripping whitespace.

  4. Apply the descriptors to the following two classes:

     class Trade:
         # ticker: NonEmptyString
         # quantity: PositiveFloat
         # price: PositiveFloat
         def __init__(self, ticker, quantity, price):
             self.ticker = ticker
             self.quantity = quantity
             self.price = price
     
     class Account:
         # account_id: NonEmptyString
         # balance: PositiveFloat
         def __init__(self, account_id, balance):
             self.account_id = account_id
             self.balance = balance
    
  5. Create a Trade instance called trade with ticker="AAPL", quantity=50.0, price=189.50.

  6. Create an Account instance called account with account_id="ACC-001", balance=10000.0.

  7. Print trade.ticker, trade.quantity, account.account_id, and account.balance.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt