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")
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.
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).
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")
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.
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).