### Installing Test Dependencies Source: https://github.com/python/mypy/blob/master/test-data/unit/README.md Install necessary dependencies for testing by running the pip install command with the test requirements file. ```bash python3 -m pip install -U -r test-requirements.txt ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/python/mypy/blob/master/docs/README.md Install Sphinx and other necessary dependencies for building the documentation from the `docs` directory. ```bash pip install -r requirements-docs.txt ``` -------------------------------- ### Example mypy.ini Configuration Source: https://github.com/python/mypy/blob/master/docs/source/config_file.md This example demonstrates a basic mypy.ini file with global options. Place this file at the root of your repository to apply these settings. ```ini # Global options: [mypy] warn_return_any = True warn_unused_configs = True ``` -------------------------------- ### Install mypy and run stubtest Source: https://github.com/python/mypy/blob/master/docs/source/stubtest.md Install mypy using pip and then run stubtest on a module to check for stub inconsistencies. Ensure mypy is installed in the same environment as the library being checked. ```shell python3 -m pip install mypy cat library.py x = "hello, stubtest" def foo(x=None): print(x) cat library.pyi x: int def foo(x: int) -> None: ... python3 -m mypy.stubtest library ``` -------------------------------- ### Install Mypy Development Build from Source Source: https://github.com/python/mypy/blob/master/docs/source/common_issues.md To install the latest development version of mypy, clone the repository and use pip to install it locally. This is useful for testing the newest features or bug fixes. ```text git clone https://github.com/python/mypy.git cd mypy python3 -m pip install --upgrade . ``` -------------------------------- ### Install Python Development Headers on Ubuntu Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md On Linux distributions like Ubuntu, install python3-dev to get CPython headers and libraries required for C extension development. ```bash $ sudo apt install python3-dev ``` -------------------------------- ### Install Missing Library Stubs Source: https://github.com/python/mypy/blob/master/docs/source/running_mypy.md Use this command to install missing stubs for a specific library. Alternatively, mypy can install all missing stubs automatically. ```text main.py:1: error: Library stubs not installed for "yaml" main.py:1: note: Hint: "python3 -m pip install types-PyYAML" main.py:1: note: (or run "mypy --install-types" to install all missing stub packages) ``` -------------------------------- ### Installing Pre-commit Hooks Source: https://github.com/python/mypy/blob/master/test-data/unit/README.md Configure pre-commit to automatically run linters on code commits by executing the install command. ```bash pre-commit install ``` -------------------------------- ### Install Mypy Source: https://github.com/python/mypy/blob/master/docs/source/getting_started.md Install mypy using pip. Requires Python 3.10 or later. ```shell $ python3 -m pip install mypy ``` -------------------------------- ### Install Mypy using pip Source: https://github.com/python/mypy/blob/master/README.md Install Mypy using pip. This command ensures you have the latest stable version of Mypy installed. ```bash python3 -m pip install -U mypy ``` -------------------------------- ### Clean Documentation Build Source: https://github.com/python/mypy/blob/master/docs/README.md Remove previously built documentation files to start a fresh build. ```bash make clean ``` -------------------------------- ### Install Dependencies for Coverage Reports Source: https://github.com/python/mypy/blob/master/test-data/unit/README.md Install necessary development headers and libraries on Debian-derived systems to build Python extension modules required for coverage reporting. ```bash apt-get install python3-dev libxml2-dev libxslt1-dev ``` -------------------------------- ### Start Mypy Daemon with Fine-Grained Cache Source: https://github.com/python/mypy/blob/master/docs/source/additional_features.md When starting or restarting the mypy daemon, use the `--use-fine-grained-cache` option to leverage the enhanced cache information. This option is passed as an argument to `dmypy start`. ```bash $ dmypy start -- --use-fine-grained-cache ``` -------------------------------- ### Install mypy-extensions Source: https://github.com/python/mypy/blob/master/docs/source/using_type_annotations.md Install or upgrade the `mypy-extensions` package using pip to enable the use of trait types. ```text pip install --upgrade mypy-extensions ``` -------------------------------- ### Start Colima Docker Runtime Source: https://github.com/python/mypy/blob/master/misc/docker/README.md Start the Colima Docker runtime, specifying the number of CPU cores to allocate. Replace '8' with your desired number of CPU cores. ```bash $ colima start -c 8 ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/python/mypy/blob/master/CONTRIBUTING.md Install test requirements and the Mypy project in editable mode. Requires Python 3.10+. ```bash python -m pip install -r test-requirements.txt python -m pip install -e . hash -r ``` -------------------------------- ### Install Mypy from GitHub repository Source: https://github.com/python/mypy/blob/master/README.md Install the latest development version of Mypy directly from its GitHub repository. This is useful for testing the newest features or bug fixes. ```bash python3 -m pip install -U git+https://github.com/python/mypy.git ``` -------------------------------- ### Install Mypy with Mypyc Support Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Install the mypy package with the 'mypyc' extra to include the mypyc compiler. Requires Python 3.10 or later. ```bash python3 -m pip install -U 'mypy[mypyc]' ``` ```bash python -m pip install -U 'mypy[mypyc]' ``` -------------------------------- ### Install Stub Packages Non-interactively Source: https://github.com/python/mypy/blob/master/docs/source/running_mypy.md Use this flag to install all suggested stub packages without a confirmation prompt, and then type check your code. This is useful for CI environments. ```text mypy --non-interactive ``` -------------------------------- ### Install Packages into Environment Source: https://github.com/python/mypy/blob/master/docs/source/running_mypy.md Confirm that you are installing packages into the expected environment by running pip with 'python -m pip'. This ensures that the correct packages are available to mypy. ```text python -m pip ... ``` -------------------------------- ### Start the mypy daemon Source: https://github.com/python/mypy/blob/master/docs/source/mypy_daemon.md Starts the mypy daemon without checking any files. You can specify mypy flags after `--`. ```bash dmypy start -- ``` -------------------------------- ### Stub File Syntax Examples Source: https://github.com/python/mypy/blob/master/docs/source/stubs.md Illustrates stub file syntax for variables, functions, and default arguments using ellipsis. ```python # Variables with annotations do not need to be assigned a value. # So by convention, we omit them in the stub file. x: int # Function bodies cannot be completely removed. By convention, # we replace them with `...` instead of the `pass` statement. def func_1(code: str) -> int: ... # We can do the same with default arguments. def func_2(a: int, b: int = ...) -> int: ... ``` -------------------------------- ### Mypy Semantic Analysis Example Source: https://github.com/python/mypy/wiki/Semantic-Analyzer This example demonstrates name binding during semantic analysis, showing how variables and functions are associated with their definitions and scopes. ```Python # mod.py x: int = 1 # Bindings: int -> builtins.int, x -> mod.x def f(x): return x + 1 # Bindings: x -> local x print(f(x)) # Bindings: print -> builtins.print, f -> mod.f, x -> mod.x ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Ensure you have the necessary tools for C extension development on macOS. ```bash $ xcode-select --install ``` -------------------------------- ### Stubtest Allowlist Entry Example Source: https://github.com/python/mypy/blob/master/docs/source/stubtest.md This is an example of a stubtest allowlist entry. It can be a simple name or a regular expression to match multiple errors. Using a regex like `(ex\.second)?` can make an error optional, useful for platform-specific issues. ```ini note: unused allowlist entry ex.second Found 1 error (checked 1 module) ``` ```ini (ex\.second)? ``` -------------------------------- ### Install typing_extensions for older Python versions Source: https://github.com/python/mypy/blob/master/docs/source/typed_dict.md If using Python versions older than 3.8, install the 'typing_extensions' package to use TypedDict. ```text python3 -m pip install --upgrade typing-extensions ``` -------------------------------- ### Class Hierarchy Example Source: https://github.com/python/mypy/wiki/Type-Checker Illustrates a simple class hierarchy used to explain type relationships in Mypy. ```python class A: def foo(self): pass class B: def bar(self): pass class AB(A, B): pass ``` -------------------------------- ### Set up Development Environment with Tox Source: https://github.com/python/mypy/blob/master/CONTRIBUTING.md Set up a development environment with all project libraries and run a command using tox. ```bash tox -e dev -- mypy --verbose test_case.py ``` ```bash tox -e dev --override testenv:dev.allowlist_externals+=env -- env ``` -------------------------------- ### Mypyc Trace Log: C API Function Call Example Source: https://github.com/python/mypy/wiki/Mypyc-Trace-Logging This log entry indicates a call to a primitive C function or a Python C API function. 'call_c' denotes this event type. Python C API functions start with 'Py', and mypyc primitive functions start with 'CPy'. ```text mypy.semanal.SemanticAnalyzer.is_func_scope:7094:call_c:CPyList_GetItemShort ``` -------------------------------- ### stubtest output for inconsistencies Source: https://github.com/python/mypy/blob/master/docs/source/stubtest.md Example output from stubtest highlighting differences between stub definitions and runtime behavior, such as default argument mismatches or type discrepancies. ```shell error: library.foo is inconsistent, runtime argument "x" has a default value but stub argument does not Stub: at line 3 def (x: builtins.int) Runtime: in file ~/library.py:3 def (x=None) error: library.x variable differs from runtime type Literal['hello, stubtest'] Stub: at line 1 builtins.int Runtime: 'hello, stubtest' ``` -------------------------------- ### Introspecting a Module with Python Interpreter Source: https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules Demonstrates using the Python interactive interpreter to inspect module contents and get help on functions. ```python >>> import os >>> dir(os) [..., 'abort', 'access', ...] # List of names defined in os >>> help(os) Help on module os: ... (contents omitted) >>> help(os.abort) Help on built-in function abort in module Posix: abort(...): abort() -> does not return! ... ``` -------------------------------- ### In-place Compilation with Setup.py Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Compile C extensions directly into the current directory using `python3 setup.py build_ext --inplace`, similar to using the `mypyc` command. ```bash python3 setup.py build_ext --inplace ``` -------------------------------- ### Install Interpreted Mypy Source: https://github.com/python/mypy/blob/master/README.md Install an interpreted version of Mypy using pip. This command ensures that Mypy is not installed from pre-compiled binaries. ```bash python3 -m pip install --no-binary mypy -U mypy ``` -------------------------------- ### Build Wheel File with Setup.py Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Create a wheel (.whl) distribution file for your package using `python3 setup.py bdist_wheel`. ```bash python3 setup.py bdist_wheel ``` -------------------------------- ### Include py.typed and stub files in setup.py for Package B Source: https://github.com/python/mypy/blob/master/docs/source/installed_packages.md Configure `setup.py` to include both the `py.typed` file and stub files (`.pyi`) for a package that has a mix of runtime and type information files. This allows mypy to use the stub files while the interpreter uses the runtime files. ```python from setuptools import setup setup( name="SuperPackageB", author="Me", version="0.1", package_data={"package_b": ["py.typed", "lib.pyi"]}, packages=["package_b"] ) ``` -------------------------------- ### Build Google Test with Make Source: https://github.com/python/mypy/blob/master/mypyc/external/googletest/README.md Use the provided Makefile to build Google Test and a sample test. This is suitable for systems with GNU make available. Navigate to the `make` directory and run `make`. ```bash cd ${GTEST_DIR}/make make ./sample1_unittest ``` -------------------------------- ### Configure setup.py for a stub-only Package C Source: https://github.com/python/mypy/blob/master/docs/source/installed_packages.md Set up `setup.py` for a stub-only package. This type of package provides type information but is not imported at runtime. It typically has a name prefixed with the runtime package name and suffixed with `-stubs`. ```python from setuptools import setup setup( name="SuperPackageC", author="Me", version="0.1", package_data={"package_c-stubs": ["__init__.pyi", "lib.pyi"]}, packages=["package_c-stubs"] ) ``` -------------------------------- ### Setup.py Integration for Mypyc Compilation Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Use `setup.py` with `mypycify` to compile Python modules into C extensions as part of your package build process. ```python from setuptools import setup from mypyc.build import mypycify setup( name='mylib', packages=['mylib'], ext_modules=mypycify([ 'mylib/__init__.py', 'mylib/mod.py', ]), ) ``` -------------------------------- ### Create and Activate Virtual Environment (Linux/macOS) Source: https://github.com/python/mypy/blob/master/CONTRIBUTING.md Create a virtual environment named 'venv' and activate it for development. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/python/mypy/blob/master/docs/README.md Build the documentation into HTML format. The output will be located in the `docs/build` directory. ```bash make html ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://github.com/python/mypy/blob/master/CONTRIBUTING.md Create a virtual environment named 'venv' and activate it for development on Windows. ```bash python -m venv venv . venv/Scripts/activate ``` -------------------------------- ### Include type information files in MANIFEST.in Source: https://github.com/python/mypy/blob/master/docs/source/installed_packages.md Add rules to `MANIFEST.in` to ensure that type information files (`.pyi` and `.typed`) are included in the source distribution (`sdist`). This is necessary in addition to `setup.py` configuration for wheels. ```text global-include *.pyi global-include *.typed ``` -------------------------------- ### Early vs. Late Binding Example Source: https://github.com/python/mypy/blob/master/docs/source/differences_from_python.md Demonstrates early binding for references within the same compilation unit and late binding for external libraries or non-final module variables. ```default from typing import Final import lib # "lib" is not compiled x = 0 y: Final = 1 def func() -> None: pass class Cls: def __init__(self, attr: int) -> None: self.attr = attr def method(self) -> None: pass def example() -> None: # Early binding: var = y func() o = Cls() o.x o.method() # Late binding: var = x # Module-level variable lib.func() # Accessing library that is not compiled ``` -------------------------------- ### Dynamically Typed Stub Example Source: https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules Example of a dynamically typed stub for a module, using 'Any' for variables, functions, and methods. ```python from typing import Any x: Any # variable def f(x, y=None): ... # function class C: def __init__(self, foo): ... # method ``` -------------------------------- ### Setup.py with Mypy Flags Source: https://github.com/python/mypy/blob/master/mypyc/doc/getting_started.md Pass mypy command-line options, such as `--disallow-untyped-defs`, to `mypycify` within your `setup.py` to enforce type checking during compilation. ```python ... setup( name='frobnicate', packages=['frobnicate'], ext_modules=mypycify([ '--disallow-untyped-defs', # Pass a mypy flag 'frobnicate.py', ]), ) ``` -------------------------------- ### Example Mypyc Trace Log Output Source: https://github.com/python/mypy/wiki/Mypyc-Trace-Logging This is an example of the line-based trace log output generated by Mypyc. Fields are separated by colons. ```text mypy.semanal.SemanticAnalyzer.flatten_lvalues::primitive_op:list_get_item_unsafe mypy.binder.ConditionalTypeBinder._get::primitive_op:int_gt mypy.semanal.SemanticAnalyzer.is_func_scope:7094:call_c:CPyList_GetItemShort mypy.typetraverser.TypeTraverserVisitor.traverse_type_tuple::primitive_op:var_object_size mypy.typeops.try_contracting_literals_in_union:1080:call_c:PyIter_Next mypy.renaming.LimitedVariableRenameVisitor.visit_name_expr:544:call_c:PySequence_Contains mypy.util.split_module_names:80:call_c:CPyList_GetItemShort mypy.expandtype.ExpandTypeVisitor.visit_instance::primitive_op:int_eq mypy.semanal.SemanticAnalyzer.process_type_annotation:3823:call_c:CPyList_GetItemShort ``` -------------------------------- ### Compile and Link Your Test (g++) Source: https://github.com/python/mypy/blob/master/mypyc/external/googletest/README.md Compile your test source file and link it with the Google Test library. Use `${GTEST_DIR}/include` in the system header search path. ```bash g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ -o your_test ``` -------------------------------- ### Show Help Message Source: https://github.com/python/mypy/blob/master/docs/source/command_line.md Display a summary of available flags and options by running mypy with -h or --help. ```bash mypy --help ``` -------------------------------- ### Mypyc Test Case Example Source: https://github.com/python/mypy/wiki/Mypyc-Development-Workflows An example of a mypyc test case using the default driver. It includes two sub-cases for list concatenation. ```python [case testConcatenateLists] def test_concat_lists() -> None: assert [1, 2] + [5, 6] == [1, 2, 5, 6] def test_concat_empty_lists() -> None: assert [] + [] == [] ``` -------------------------------- ### Initialize CMake Build Directory Source: https://github.com/python/mypy/blob/master/mypyc/external/googletest/README.md Set up a build directory and generate native build scripts using CMake. This command configures the build for Google Test. ```bash mkdir mybuild # Create a directory to hold the build output. cd mybuild cmake ${GTEST_DIR} # Generate native build scripts. ``` -------------------------------- ### Stubtest CLI: --help Option Source: https://github.com/python/mypy/blob/master/docs/source/stubtest.md Displays the help message for stubtest, providing an overview of all available command-line options and their usage. ```bash stubtest --help ``` -------------------------------- ### Mypy: Fast Module Lookup Example Structure Source: https://github.com/python/mypy/blob/master/docs/source/command_line.md Illustrates a directory structure that might trigger the quadratic worst-case behavior in mypy's default import scanning, where `--fast-module-lookup` can provide a performance improvement. ```default foo/ company/ foo/ a.py bar/ company/ bar/ b.py baz/ company/ baz/ c.py ... ``` -------------------------------- ### Basic Mypy Example Source: https://github.com/python/mypy/blob/master/docs/source/index.md This example demonstrates a common error that Mypy can detect. It shows a string concatenation with an integer, which Mypy flags as an unsupported operand type. ```python number = input("What is your favourite number?") print("It is", number + 1) # error: Unsupported operand types for + ("str" and "int") ``` -------------------------------- ### Initialize CMake Build with Samples Source: https://github.com/python/mypy/blob/master/mypyc/external/googletest/README.md Configure the CMake build to include Google Test samples. This command generates build scripts that will compile the sample tests along with the library. ```bash cmake -Dgtest_build_samples=ON ${GTEST_DIR} ``` -------------------------------- ### Installing Stub Packages via Pip Source: https://github.com/python/mypy/blob/master/docs/source/getting_started.md Provides the command-line instruction to install stub packages for libraries, which enables mypy to type check code that uses these libraries. ```shell $ python3 -m pip install types-PyYAML types-requests ``` -------------------------------- ### Check Documentation Links Source: https://github.com/python/mypy/blob/master/docs/README.md Test and verify all the links within the documentation to ensure they are valid. ```bash make linkcheck ``` -------------------------------- ### Example of disallowing entirely unannotated function definitions Source: https://github.com/python/mypy/blob/master/docs/source/config_file.md This example shows a function definition that would trigger an error with `disallow_untyped_defs` enabled, as neither parameter has a type annotation. ```python def f(a, b) ``` -------------------------------- ### Example of disallowing incomplete function definitions Source: https://github.com/python/mypy/blob/master/docs/source/config_file.md This example demonstrates a function definition that would trigger an error with `disallow_incomplete_defs` enabled, due to one parameter having a type annotation while the other does not. ```python def f(a: int, b) ``` -------------------------------- ### Example pyproject.toml Configuration Source: https://github.com/python/mypy/blob/master/docs/source/config_file.md This TOML file demonstrates how to configure mypy globally and for specific modules using pyproject.toml. It includes settings for Python version, warnings, exclusions, and per-module overrides. ```toml # mypy global options: [tool.mypy] python_version = "3.10" warn_return_any = true warn_unused_configs = true exclude = [ '^file1\.py$', # TOML literal string (single-quotes, no escaping necessary) "^file2\\.py$", # TOML basic string (double-quotes, backslash and other characters need escaping) ] # mypy per-module options: [[tool.mypy.overrides]] module = "mycode.foo.*" disallow_untyped_defs = true [[tool.mypy.overrides]] module = "mycode.bar" warn_return_any = false [[tool.mypy.overrides]] module = [ "somelibrary", "some_other_library" ] ignore_missing_imports = true ``` -------------------------------- ### Specify Python Executable Source: https://github.com/python/mypy/blob/master/docs/source/running_mypy.md If mypy is running in a different environment than where packages are installed, use this flag to point to the correct Python executable. This ensures mypy can find installed packages. ```text mypy --python-executable ``` -------------------------------- ### Python Code Snippet for Inspection Examples Source: https://github.com/python/mypy/blob/master/docs/source/mypy_daemon.md This Python code defines functions and variables used in the `dmypy inspect` examples. It serves as the target code for demonstrating expression inspection. ```python def foo(x: int, longer_name: str) -> None: x longer_name ``` -------------------------------- ### Python Type Error Example Source: https://github.com/python/mypy/blob/master/README.md This example demonstrates a common type error in Python that Mypy can detect. It shows an unsupported operand type for the '+' operator between a string and an integer. ```python number = input("What is your favourite number?") print("It is", number + 1) # error: Unsupported operand types for + ("str" and "int") ``` -------------------------------- ### Compile Google Test Library (g++) Source: https://github.com/python/mypy/blob/master/mypyc/external/googletest/README.md Compile the Google Test source file and create a static library. Ensure `${GTEST_DIR}/include` is in the system header search path and `${GTEST_DIR}` is in the normal search path. The `-pthread` flag is required as Google Test uses threads. ```bash g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -pthread -c ${GTEST_DIR}/src/gtest-all.cc ar -rv libgtest.a gtest-all.o ``` -------------------------------- ### No Strict Bytes Example Source: https://github.com/python/mypy/blob/master/docs/source/command_line.md Shows how `--no-strict-bytes` treats bytearray and memoryview as subtypes of bytes, which differs from runtime behavior. The example also presents an alternative using `collections.abc.Buffer` for broader compatibility. ```python def f(buf: bytes) -> None: assert isinstance(buf, bytes) # Raises runtime AssertionError with bytearray/memoryview with open("binary_file", "wb") as fp: fp.write(buf) # Using --no-strict-bytes disables the following errors f(bytearray(b"")) # Argument 1 to "f" has incompatible type "bytearray"; expected "bytes" f(memoryview(b"")) # Argument 1 to "f" has incompatible type "memoryview"; expected "bytes" # If `f` accepts any object that implements the buffer protocol, # consider using Buffer instead: from collections.abc import Buffer # "from typing_extensions" in Python 3.11 and earlier def f(buf: Buffer) -> None: with open("binary_file", "wb") as fp: fp.write(buf) f(b"") # Ok f(bytearray(b"")) # Ok f(memoryview(b"")) # Ok ``` -------------------------------- ### Include py.typed in setup.py for Package A Source: https://github.com/python/mypy/blob/master/docs/source/installed_packages.md Configure `setup.py` to include the `py.typed` file for a package that ships inline type annotations. This ensures the type information is distributed with the package. ```python from setuptools import setup setup( name="SuperPackageA", author="Me", version="0.1", package_data={"package_a": ["py.typed"]}, packages=["package_a"] ) ``` -------------------------------- ### Protocol Attribute Invariance Example Source: https://github.com/python/mypy/blob/master/docs/source/protocols.md Protocol attributes are invariant. This example demonstrates a type error when a class with a more specific attribute type is assigned to a protocol expecting a broader type, due to mutability. ```python class Box(Protocol): content: object class IntBox: content: int def takes_box(box: Box) -> None: ... takes_box(IntBox()) # error: Argument 1 to "takes_box" has incompatible type "IntBox"; expected "Box" # note: Following member(s) of "IntBox" have conflicts: # note: content: expected "object", got "int" ``` -------------------------------- ### Mypy Errors for Missing Library Stubs Source: https://github.com/python/mypy/blob/master/docs/source/getting_started.md Illustrates typical mypy error messages when type stubs are not installed for third-party libraries like 'yaml' and 'requests'. It suggests installing stub packages as a solution. ```text prog.py:1: error: Library stubs not installed for "yaml" prog.py:1: note: Hint: "python3 -m pip install types-PyYAML" prog.py:2: error: Library stubs not installed for "requests" prog.py:2: note: Hint: "python3 -m pip install types-requests" ... ``` -------------------------------- ### Navigate to Repository Directory Source: https://github.com/python/mypy/wiki/Using-Git-And-GitHub Change your current working directory to the cloned mypy repository. ```bash $ cd mypy ``` -------------------------------- ### Building a Debug Version of CPython Source: https://github.com/python/mypy/blob/master/mypyc/doc/dev-intro.md Instructions for building a debug version of CPython on Ubuntu, including installing dependencies, configuring with '--with-pydebug', and setting up a virtual environment. ```bash $ sudo apt install gdb build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev libbz2-dev libffi-dev libgdbm-compat-dev $ $ cd Python-3.XX.Y $ ./configure --with-pydebug $ make -s -j16 $ ./python -m venv ~/ # Use ./python.exe -m venv ... on macOS $ source ~//bin/activate $ cd $ pip install -r test-requirements.txt ``` -------------------------------- ### Stub for Python Builtins Source: https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules Examples of stub definitions for built-in Python variables and functions. ```python True: bool False: bool ... ``` ```python def chr(code: int) -> str: ... ``` -------------------------------- ### Python module source code Source: https://github.com/python/mypy/blob/master/docs/source/stubgen.md Example Python source file for which stubgen can generate a stub. ```python from other_module import dynamic BORDER_WIDTH = 15 class Window: parent = dynamic() def __init__(self, width, height): self.width = width self.height = height def create_empty() -> Window: return Window(0, 0) ``` -------------------------------- ### Stub for unittest.TestSuite Class Source: https://github.com/python/mypy/wiki/Creating-Stubs-For-Python-Modules Example of a stub definition for a Python class, including its constructor and methods. ```python class TestSuite(Testable): def __init__(self, tests: Iterable[Testable] = None) -> None: ... def addTest(self, test: Testable) -> None: ... def addTests(self, tests: Iterable[Testable]) -> None: ... def run(self, result: TestResult) -> None: ... def debug(self) -> None: ... def countTestCases(self) -> int: ... ``` -------------------------------- ### Mypy import error example Source: https://github.com/python/mypy/blob/master/docs/source/running_mypy.md When using `--follow-imports=error`, mypy will flag ignored imports with a note. ```text main.py:1: note: Import of "mycode.bar" ignored main.py:1: note: (Using --follow-imports=error, module not passed on command line) ``` -------------------------------- ### Profile Mypy with py-spy Source: https://github.com/python/mypy/wiki/Profiling-and-Optimizing-Mypy Install `py-spy` and `mypy` to record profiling data. Use `--native` for native code profiling and `-f speedscope` to output in a format compatible with speedscope.app. Replace `-c 'import os'` with your actual Mypy command. ```shell $ pip install py-spy $ pip install mypy $ py-spy record --native -f speedscope -o profile.dat -- mypy -c 'import os' ``` -------------------------------- ### Restart the mypy daemon Source: https://github.com/python/mypy/blob/master/docs/source/mypy_daemon.md Restarts the mypy daemon, applying any specified flags. This is equivalent to stopping and then starting the daemon. ```bash dmypy restart -- ``` -------------------------------- ### TypedDict Inheritance Example Source: https://github.com/python/mypy/blob/master/docs/source/typed_dict.md Demonstrates inheritance in TypedDict, where 'BookBasedMovie' inherits keys from 'Movie' and adds its own 'based_on' key. ```python class Movie(TypedDict): name: str year: int class BookBasedMovie(Movie): based_on: str ``` -------------------------------- ### Mypy Plugin Entry Point Source: https://github.com/python/mypy/blob/master/docs/source/extending_mypy.md Define a plugin class inheriting from `mypy.plugin.Plugin` and an entry point function that returns an instance of this class. The entry point function accepts the Mypy version string. ```python from mypy.plugin import Plugin class CustomPlugin(Plugin): def get_type_analyze_hook(self, fullname: str): # see explanation below ... def plugin(version: str): # ignore version argument if the plugin works with all mypy versions. return CustomPlugin ``` -------------------------------- ### Union Type Hierarchy Example Source: https://github.com/python/mypy/wiki/Type-Checker Depicts a hierarchy involving Union types to demonstrate meet and join operations. ```python Union[A, B, C] <- Union[B, C] <- C ^ | Union[A, B] <- ^ | A ``` -------------------------------- ### CI Script for Mypy Source: https://github.com/python/mypy/blob/master/docs/source/existing_code.md A basic Continuous Integration script to install and run mypy. Ensure consistent options and file checking by using a configuration file and specifying the code to be checked. ```text python3 -m pip install mypy==1.8 # Run your standardised mypy invocation, e.g. mypy my_project # This could also look like `scripts/run_mypy.sh`, `tox run -e mypy`, `make mypy`, etc ``` -------------------------------- ### Defining a User-Defined Protocol: SupportsClose Source: https://github.com/python/mypy/blob/master/docs/source/protocols.md Illustrates how to define a custom protocol `SupportsClose` by inheriting from `typing.Protocol` and specifying required methods. Shows that a class implementing the method is structurally compatible, even without explicit inheritance. ```python from collections.abc import Iterable from typing import Protocol class SupportsClose(Protocol): # Empty method body (explicit '...') def close(self) -> None: ... class Resource: # No SupportsClose base class! def close(self) -> None: self.resource.release() # ... other methods ... def close_all(items: Iterable[SupportsClose]) -> None: for item in items: item.close() close_all([Resource(), open('some/file')]) # OK ```