Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python Class Subscription Code

Practice implementing __class_getitem__ for class subscription and generic-style parameterization.

Advanced ~9 min read

Challenge 1

Implement class subscription so Box[int] returns a tuple containing the class name and the supplied item.

python Your answer
class Box:
    def __class_getitem__(cls, item):
        

print(Box[int])

Press Ctrl⌘Enter to check your answer

Challenge 2

Normalize a single-or-multiple type argument into a tuple before building the result.

python Your answer
class Pair:
    def __class_getitem__(cls, key):
        if not isinstance(key, tuple):
            key = (key,)
        
        return tuple(item.__name__ for item in key)

print(Pair[int, str])

Press Ctrl⌘Enter to check your answer

Challenge 3

Return a GenericAlias so Box[int] has a parameterized runtime representation.

python Your answer
from types import GenericAlias

class Box:
    def __class_getitem__(cls, item):
        

print(Box[int])
print(Box[int].__args__)

Press Ctrl⌘Enter to check your answer

Challenge 4

Implement the class-level hook without changing the existing instance subscription method.

python Your answer
class Catalog:
    def __class_getitem__(cls, key):
        

    def __getitem__(self, key):
        return key * 10

print(Catalog[int])
print(Catalog()[2])

Press Ctrl⌘Enter to check your answer