w3resource

Python Metaclass Tutorial: Convert Attribute Names to Uppercase

Python Metaprogramming: Exercise-1 with Solution

Basic Metaclass:

Write a Python program to create a metaclass “UpperAttrMeta” that converts all attribute names of a class to uppercase.

Sample Solution:

Python Code :

# Define a metaclass that converts all attribute names to uppercase
class UpperAttrMeta(type):
    def __new__(cls, name, bases, dct):
        # Create a new dictionary to store uppercase attributes
        uppercase_attr = {}
        for name, value in dct.items():
            if not name.startswith('__'):
                # Convert attribute name to uppercase
                uppercase_attr[name.upper()] = value
            else:
                # Preserve special methods as they are
                uppercase_attr[name] = value
        # Create the new class with modified attributes
        return super().__new__(cls, name, bases, uppercase_attr)

# Create a class using the metaclass
class MyClass(metaclass=UpperAttrMeta):
    foo = 'bar'
    baz = 'qux'

# Test the class
print(hasattr(MyClass, 'foo'))  # False, because attribute names are uppercase
print(hasattr(MyClass, 'FOO'))  # True, because 'foo' is converted to 'FOO'
print(MyClass.FOO)  # 'bar', accessing the uppercase attribute

Output:

False
True
bar

Explanation:

  • Metaclass Definition:
    • UpperAttrMeta is a metaclass that overrides the 'new' method.
    • It creates a new dictionary 'uppercase_attr' where all attribute names (except special methods starting with __) are converted to uppercase.
  • Class Creation:
    • MyClass is defined to use 'UpperAttrMeta' as its metaclass.
    • Attributes 'foo' and 'baz' in 'MyClass' are automatically converted to 'FOO' and 'BAZ'.
  • Testing the Class:
    • The test checks if 'foo' exists in 'MyClass' (it does not, because it was converted to uppercase).
    • It then checks if 'FOO' exists (it does) and prints its value ('bar').

Python Code Editor :

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

Previous: Python Metaprogramming Exercises Home.
Next: Python Metaclass Tutorial: Validate Attributes as Integers

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/metaprogramming/python-metaprogramming-exercise-1.php