Python Metaclass Tutorial: Validate Attributes as Integers

Python Metaprogramming: Exercise-2 with Solution

Validating Attributes with Metaclass:

Write a Python program to create a metaclass “ValidateAttrMeta” that ensures all attributes of a class are integers. Raise a TypeError if any attribute is not an integer.

Sample Solution:

Python Code :

# Define a metaclass that ensures all attributes are integers
class ValidateAttrMeta(type):
    # Override the __new__ method of the metaclass
    def __new__(cls, name, bases, dct):
        # Iterate over all attributes of the class
        for key, value in dct.items():
            # Check if the attribute is not a special method and is not an integer
            if not key.startswith('__') and not isinstance(value, int):
                # Raise a TypeError if the attribute is not an integer
                raise TypeError(f"Attribute {key} is not an integer")
        # Create the new class with validated attributes
        return super().__new__(cls, name, bases, dct)

# Create a class using the metaclass
class MyIntClass(metaclass=ValidateAttrMeta):
    # Define an integer attribute
    foo = 100
    # Define another integer attribute
    bar = 200
    # Define a non-integer attribute (uncomment to test the TypeError)
    # baz = 'not an integer'  # Uncommenting this should raise a TypeError

# Test the class
# Print the value of attribute foo
print(MyIntClass.foo)  # 100
# Print the value of attribute bar
print(MyIntClass.bar)  # 200




  • Metaclass Definition:
    • ValidateAttrMeta is a metaclass that overrides the 'new' method.
    • In the 'new' method, it iterates over all class attributes.
    • If an attribute is not a special method (doesn't start with __) and is not an integer, it raises a TypeError.
  • Class Creation:
    • MyIntClass uses 'ValidateAttrMeta' as its metaclass.
    • Attributes 'foo' and 'bar' are valid integers, so the class is created successfully.
    • Uncommenting the line defining 'baz' as a non-integer would raise a 'TypeError' during class creation.
  • Testing the Class:
    • The test code prints the values of the attributes 'foo' and 'bar'.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Metaclass Tutorial: Convert Attribute Names to Uppercase.
Next: Python Singleton Metaclass: Ensure One Instance

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.