Type Hinting: Argument Of Type Class

Question:

I’m defining a method

def foo_my_class(my_class: ???, bar: str) -> None:
    """ Operate on my_class """

I wonder, how can I use type hinting feature to specify that class should be passed in the first argument.

Basically, what should I put instead of ??? mark up there?

Here is some more code to be more specific on what I am trying to achieve.

class Base(object):
   """base class"""

class X(Base):
    """some class"""

class Y(Base):
    """some other class"""   

foo_my_class(X, "foo")    
foo_my_class(Y, "bar")
Asked By: anti1869

||

Answers:

I could be wrong, as I haven’t been getting down and dirty in Python 3.5 as yet, but looking at the documentation you should be able to do it with typing.Optional. A brief example.

>>> from typing import Optional
>>> 
>>> class MyClass(object):
>>>     def __init__(self):
>>>         self.a = 1
>>> 
>>> O = Optional[MyClass]
>>> 
>>> def test(x: O) -> int:
>>>     return x.a
>>> 
>>> myclass = MyClass()
>>> print test(myclass)
1

Hope that helps.

Answered By: Christian Witts

You just use the class itself.

def foo_my_class(my_class: MyClass, bar: str) -> None:

From the PEP (emphasis mine):

Type hints may be built-in classes (including those defined in standard library or third-party extension modules), abstract base classes, types available in the types module, and user-defined classes (including those defined in the standard library or third-party modules).

Answered By: Daniel Roseman

As explained here, you can use Type:

from typing import Type

class X:
    """some class"""

def foo_my_class(my_class: Type[X], bar: str) -> None:
    """ Operate on my_class """
Answered By: roipoussiere
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.