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 """
Answer from roipoussiere on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original, which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost. Added in version 3.5.2. Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function. Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.
🌐
Dagster
dagster.io › blog › python-type-hinting
Using Type Hinting in Python Projects
For example, if a variable can ... This function can handle either a string or an integer · The Any class is used to indicate that a variable can be of any type....
🌐
Reddit
reddit.com › r/learnpython › type-hinting with user defined classes
r/learnpython on Reddit: Type-hinting with user defined classes
November 14, 2023 -

I have two custom classes, one of which requires the other as an input argument.

class Authentication(object):
    def __init__(self) -> None:
        self.auth_data = self._resolve_auth()

class Data(object):
    def __init__(self, authentication) -> None:
        self.baseurl = authentication.baseurl
        self.token = authentication.token

I have the Authentication class defined in a seperate file in my project. So my question is, if I want to apply type-hinting to the Data class i.e.

def __init__(self, authentication: Authentication) -> None:

How do I go about doing this without having to import the Authentication class into my file which contains the Data class? It seems like overkill just to get proper type-hinting.

🌐
Adam Johnson
adamj.eu › tech › 2021 › 05 › 16 › python-type-hints-return-class-not-instance
Python type hints: specify a class rather than an instance thereof - Adam Johnson
In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing.Type).
🌐
Mypy
mypy.readthedocs.io › en › stable › cheat_sheet_py3.html
Type hints cheat sheet - mypy 1.19.1 documentation
# Another option is to just put the type in quotes def f(foo: 'A') -> int: # Also ok ... class A: # This can also come up if you need to reference a class in a type # annotation inside the definition of that class @classmethod def create(cls) -> A: ... See Class name forward references for more details. Decorator functions can be expressed via generics. See Declaring decorators for more details. Example using Python 3.12 syntax:
🌐
Python
peps.python.org › pep-0484
PEP 484 – Type Hints | peps.python.org
The minimum requirement is to handle the builtin decorators @property, @staticmethod and @classmethod. The syntax leverages PEP 3107-style annotations with a number of extensions described in sections below. In its basic form, type hinting is used by filling function annotation slots with classes:
🌐
Codefinity
codefinity.com › blog › A-Comprehensive-Guide-to-Python-Type-Hints
A Comprehensive Guide to Python Type Hints
Q: Is it possible to create custom type hints? A: Yes, you can create custom type hints using classes or by using TypeVar for creating generic types in Python.
Find elsewhere
🌐
Readthedocs
python-type-checking.readthedocs.io › en › latest › types.html
Type Classes — Guide to Python Type Checking 1.0 documentation
The first thing to understand is that type annotations are actual python classes. You must import them from typing to use them. This is admittedly a bit of a nuisance, but it makes more sense when you consider that the syntax integration in python 3.5 means you’re attaching objects to function definitions just as you do when providing a default value to an argument. In fact, you can use typing.get_type_hints() function to inspect type hint objects on a function at runtime, just as you would inspect argument defaults with inspect.getargspec().
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
Get started with Python type hints | InfoWorld
June 18, 2025 - (We’d normally make such a thing into a method for the class, but it’s broken out separately here for illustration.) Also note we have the __init__ method type-hinted; name is hinted as str. We do not need to hint self; the default behavior with Python linting is to assume self is the class.
🌐
Cpske
cpske.github.io › ISP › type-hints › introduction
Type Hints –– An Introduction | Individual Software Process
Python typing Package - the type hints you can use to designate Python types Python Collection Base Classes in the package collections.abc.
Top answer
1 of 2
287

The former is correct, if arg accepts an instance of CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

In case you want the class CustomClass itself (or a subtype), then you should write:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

Like it is written in the documentation about Typing:

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves - specifically, it will accept the class object of C.

The documentation includes an example with the int class:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

Update 2024: Type is now deprecated in favour of type

2 of 2
41

Willem Van Onsem's answer is of course correct, but I'd like to offer a small update. In PEP 585, type hinting generics were introduced in standard collections. For example, whereas we previously had to say e.g.

from typing import Dict

foo: Dict[str, str] = { "bar": "baz" }

we can now forgo the parallel type hierarchy in the typing module and simply say

foo: dict[str, str] = { "bar": "baz" }

This feature is available in python 3.9+, and also in 3.7+ if using from __future__ import annotations.

In terms of this specific question, it means that instead of from typing import Type, we can now simply annotate classes using the built-in type:

def FuncA(arg: type[CustomClass]):
🌐
JetBrains
jetbrains.com › help › pycharm › type-hinting-in-product.html
Type hinting in PyCharm | PyCharm Documentation
Select Add type hint for .... Press Enter to complete the action or edit the type if appropriate. You can also use Python stubs to specify the types of variables, functions, and class fields.
Top answer
1 of 9
1795

I guess you got this exception:

NameError: name 'Position' is not defined

This is because in the original implementation of annotations, Position must be defined before you can use it in an annotation.

Python 3.14+: It'll just work

Python 3.14 has a new, lazily evaluated annotation implementation specified by PEP 749 and 649. Annotations will be compiled to special __annotate__ functions, executed when an object's __annotations__ dict is first accessed instead of at the point where the annotation itself occurs.

Thus, annotating your function as def __add__(self, other: Position) -> Position: no longer requires Position to already exist:

class Position:
    def __add__(self, other: Position) -> Position:
        ...

Python 3.7+, deprecated: from __future__ import annotations

from __future__ import annotations turns on an older solution to this problem, PEP 563, where all annotations are saved as strings instead of as __annotate__ functions or evaluated values. This was originally planned to become the default behavior, and almost became the default in 3.10 before being reverted.

With the acceptance of PEP 749, this will be deprecated in Python 3.14, and it will be removed in a future Python version. Still, it works for now:

from __future__ import annotations

class Position:
    def __add__(self, other: Position) -> Position:
        ...

Python 3+: Use a string

This is the original workaround, specified in PEP 484. Write your annotations as string literals containing the text of whatever expression you originally wanted to use as an annotation:

class Position:
    def __add__(self, other: 'Position') -> 'Position':
        ...

from __future__ import annotations effectively automates doing this for all annotations in a file.

typing.Self might sometimes be appropriate

Introduced in Python 3.11, typing.Self refers to the type of the current instance, even if that type is a subclass of the class the annotation appears in. So if you have the following code:

from typing import Self

class Parent:
    def me(self) -> Self:
        return self

class Child(Parent): pass

x: Child = Child().me()

then Child().me() is treated as returning Child, instead of Parent.

This isn't always what you want. But when it is, it's pretty convenient.

For Python versions < 3.11, if you have typing_extensions installed, you can use:

from typing_extensions import Self

Sources

The relevant parts of PEP 484, PEP 563, and PEP 649, to spare you the trip:

Forward references

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

A situation where this occurs commonly is the definition of a container class, where the class being defined occurs in the signature of some of the methods. For example, the following code (the start of a simple binary tree implementation) does not work:

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

To address this, we write:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

The string literal should contain a valid Python expression (i.e., compile(lit, '', 'eval') should be a valid code object) and it should evaluate without errors once the module has been fully loaded. The local and global namespace in which it is evaluated should be the same namespaces in which default arguments to the same function would be evaluated.

and PEP 563, deprecated:

Implementation

In Python 3.10, function and variable annotations will no longer be evaluated at definition time. Instead, a string form will be preserved in the respective __annotations__ dictionary. Static type checkers will see no difference in behavior, whereas tools using annotations at runtime will have to perform postponed evaluation.

...

Enabling the future behavior in Python 3.7

The functionality described above can be enabled starting from Python 3.7 using the following special import:

from __future__ import annotations

and PEP 649:

Overview

This PEP adds a new dunder attribute to the objects that support annotations–functions, classes, and modules. The new attribute is called __annotate__, and is a reference to a function which computes and returns that object’s annotations dict.

At compile time, if the definition of an object includes annotations, the Python compiler will write the expressions computing the annotations into its own function. When run, the function will return the annotations dict. The Python compiler then stores a reference to this function in __annotate__ on the object.

Furthermore, __annotations__ is redefined to be a “data descriptor” which calls this annotation function once and caches the result.

Things that you may be tempted to do instead

A. Define a dummy Position

Before the class definition, place a dummy definition:

class Position(object):
    pass

class Position:

    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __add__(self, other: Position) -> Position:
        return Position(self.x + other.x, self.y + other.y)

This will get rid of the NameError and may even look OK:

>>> Position.__add__.__annotations__
{'other': __main__.Position, 'return': __main__.Position}

But is it?

>>> for k, v in Position.__add__.__annotations__.items():
...     print(k, 'is Position:', v is Position)                                                                                                                                                                                                                  
return is Position: False
other is Position: False

And mypy will report a pile of errors:

main.py:4: error: Name "Position" already defined on line 1  [no-redef]
main.py:11: error: Too many arguments for "Position"  [call-arg]
main.py:11: error: "Position" has no attribute "x"  [attr-defined]
main.py:11: error: "Position" has no attribute "y"  [attr-defined]
Found 4 errors in 1 file (checked 1 source file)

B. Monkey-patch in order to add the annotations:

You may want to try some Python metaprogramming magic and write a decorator to monkey-patch the class definition in order to add annotations:

class Position:
    ...
    def __add__(self, other):
        return self.__class__(self.x + other.x, self.y + other.y)

The decorator should be responsible for the equivalent of this:

Position.__add__.__annotations__['return'] = Position
Position.__add__.__annotations__['other'] = Position

It'll work right at runtime:

>>> for k, v in Position.__add__.__annotations__.items():
...     print(k, 'is Position:', v is Position)                                                                                                                                                                                                                  
return is Position: True
other is Position: True

But static analyzers like mypy won't understand it, and static analysis is the biggest use case of type annotations.

2 of 9
224

PEP 673 which is implemented in Python 3.11, adds the Self type.

from typing import Self    

class Position:

    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y

    def __add__(self, other: Self) -> Self:
        return type(self)(self.x + other.x, self.y + other.y)

Returning Self is often a good idea, but you must return an object of the same type as self, which means calling type(self) rather than Position.


For older versions of Python (currently 3.7 and later), use the typing-extensions package. One of its purposes is to

Enable use of new type system features on older Python versions. For example, typing.TypeGuard is new in Python 3.10, but typing_extensions allows users on previous Python versions to use it too.

Then you just import from typing_extensions instead of typing, e.g. from typing_extensions import Self.

🌐
Real Python
realpython.com › python-type-self
Python's Self Type: How to Annotate Methods That Return self – Real Python
June 10, 2023 - You annotate SavingsAccount.from_application() with the TBankAccount type variable, and you annotate the cls parameter with type[TBankAccount]. Most static type checkers should recognize this as valid type hinting for both BankAccount and SavingsAccount. The main drawback is that TypeVar is verbose, and a developer can easily forget to instantiate a TypeVar instance or properly bind the instance to a class.
🌐
Real Python
realpython.com › ref › glossary › type-hint
type hint | Python Glossary – Real Python
In Python, a type hint is a syntactic construct that allows you to indicate the expected data types of variables, function arguments, and return values.
🌐
Reddit
reddit.com › r/learnpython › type hints in class using class attributes
r/learnpython on Reddit: Type hints in class using class attributes
December 3, 2023 -

I have a class I'm building as a learning tool. It's designed to be subclassed and so it's got some stuff built in to help with that. I'd like to assign an attribute within the class that could be changed when subclassing (or left as the default value), and want to use that to type hint the methods within the class, so that when subclassed it adjusts the type hints to suit the subclass.

class Coord:
    """A generic coordinate class"""
    pass


class 2DCoord:
    """2D coordinates"""
    pass


class Grid:
    coord_type: type[Coord] = Coord

    def some_method(arg: Self.coord_type) -> None:
        pass


class 2DGrid(Grid):
    coord_type = 2DCoord

I want 2DGrid().some_method(arg) to expect a 2DCoord instance as its argument. Self.coord_type is highlighted as an invalid reference in PyCharm because typing.Self doesn't have a coord_type attribute. Is there a correct way to do this? Or is this meant to work but PyCharm isn't interpreting it correctly?