1

I am trying to define a new type hint, however, it will not let me do this in Python 3.6 and I was wondering if there is any way around it. Here is my example code where I want my own class which takes a list as a field:

class T(type):

    def __new__(cls, nums):
        return super().__new__(cls, f'T((nums))', (T,),{})

    def __init__(self, nums):
        self.__origin__ = T
        self.__args__ = nums

whenever I try to actually use this, I get

'type' object is not subscriptable

If I define a custom type hint that does not involve a list, the code works. Is there anyway I can define a custom type hint in python3.6?

1 Answer 1

2

You need to understand that type hints are for objects (or datatypes). You can not create a custom class inheriting from type. If you want to create a new datatype, then simply inherit from object. Although, even inheriting from object is not necessary as everything is an object in python but it is generally considered as a good practice.

class T(object):
  def __init__(self, val):
    self.__val = val

  def __str__(self):
    return self.__val

t = T(10)
print(t) # 10
print(type(t)) # <class '__main__.T'>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.