0

I was working with namedtuples and learned something that I found odd at first. Still not quite sure how or why this works and what can be the use of this:

from collections import namedtuple
Card = namedtuple('Card', ['rank', 'suit'])

Above code works fine and creates a new Class - Card, which is a subclass of tuple class.

Now when I do this:

newCard = Card('7', 'Hearts')

It serves my purpose of creating a new card. But when I do this:

newCard = Card['7', 'Hearts']

It does not work as expected but also does not throw any error. Normally, Types are not subscriptable and if I try the same with any other class:

class FrenchDeck:
      Pass

newDeck = FrenchDeck[1]

It throws following error:

Traceback (most recent call last):
  File "C:\Users\sbvik\PycharmProjects\pythonProject\Chapter1.py", line 27, in <module>
    c = FrenchDeck[1]
TypeError: 'type' object is not subscriptable

But if I inherit my FrenchDeck class like this:

class FrenchDeck(tuple):
      Pass

newDeck = FrenchDeck[1]

No error is thrown.

Then I checked the type of newDeck it turns out to be <class 'types.GenericAlias'>

I am not sure what 'types.GenericAlias' means, what's its purpose and how is it used? Also, why was TypeError: 'type' object is not subscriptable not thrown in this case?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
pangna
  • 61
  • 4

0 Answers0