├── setup.cfg ├── .flake8 ├── musttyping ├── whitelist.py ├── printer.py ├── __init__.py └── core.py ├── main.py ├── pyproject.toml ├── LICENSE ├── setup.py ├── README.md └── .gitignore /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | -------------------------------------------------------------------------------- /musttyping/whitelist.py: -------------------------------------------------------------------------------- 1 | # TODO: deal with debug function inserted by PyCharm 2 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import musttyping 2 | 3 | 4 | def f(): 5 | def f(): 6 | ... 7 | 8 | ... 9 | 10 | 11 | musttyping.must_typing() 12 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "musttyping" 3 | repository = "https://github.com/zkonge/musttyping" 4 | 5 | [tool.black] 6 | line-length = 120 7 | target-version = ['py37', 'py38', 'py39'] 8 | include = '\.pyi?$' 9 | -------------------------------------------------------------------------------- /musttyping/printer.py: -------------------------------------------------------------------------------- 1 | from inspect import getfile, getsourcelines 2 | from sys import stderr 3 | from types import FunctionType 4 | 5 | 6 | def print_function_context(f: FunctionType) -> None: 7 | name, file, (source, source_line_number) = f.__name__, getfile(f), getsourcelines(f) 8 | 9 | print(f"Function '{name}' located in {file} at line {source_line_number}", file=stderr) 10 | print(">>", "".join(source[:5]), file=stderr) 11 | -------------------------------------------------------------------------------- /musttyping/__init__.py: -------------------------------------------------------------------------------- 1 | from gc import get_objects 2 | from sys import stderr 3 | from types import FunctionType 4 | 5 | from .core import need_typing 6 | from .printer import print_function_context 7 | 8 | __all__ = ('LackAnnotationException', 'must_typing') 9 | 10 | 11 | class LackAnnotationException(Exception): 12 | pass 13 | 14 | 15 | def must_typing() -> None: 16 | for obj in get_objects(): 17 | if callable(obj): 18 | lack_type = need_typing(obj) 19 | if lack_type: 20 | assert isinstance(obj, FunctionType), "obj is not FunctionType, please feedback to musttyping author" 21 | print_function_context(obj) 22 | print(f">> It lack of {lack_type.name} type annotation <<", file=stderr) 23 | raise LackAnnotationException(f"{obj} need type annotation(s)") 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Konge 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from setuptools import setup, find_packages 3 | 4 | CURRENT_DIR = Path(__file__).parent 5 | LONG_DESCRIPTION = (CURRENT_DIR / "README.md").read_text(encoding="utf-8") 6 | 7 | setup( 8 | name="musttyping", 9 | version='0.0.1', 10 | description="Force you (or your user) annotate function types.", 11 | long_description=LONG_DESCRIPTION, 12 | long_description_content_type="text/markdown", 13 | author="zkonge", 14 | author_email="zkonge@outlook.com", 15 | url="https://github.com/zkonge/musttyping", 16 | packages=find_packages(), 17 | license="MIT", 18 | keywords="typing", 19 | python_requires=">=3.6", 20 | classifiers=[ 21 | "Development Status :: 4 - Beta", 22 | "Environment :: Console", 23 | "Intended Audience :: Developers", 24 | "License :: OSI Approved :: MIT License", 25 | "Operating System :: OS Independent", 26 | "Natural Language :: English", 27 | "Programming Language :: Python :: 3.6", 28 | "Programming Language :: Python :: 3.7", 29 | "Programming Language :: Python :: 3.8", 30 | "Programming Language :: Python :: 3.9", 31 | "Programming Language :: Python :: 3.10", 32 | "Programming Language :: Python :: 3 :: Only", 33 | "Topic :: Software Development :: Libraries :: Python Modules", 34 | "Topic :: Software Development :: Quality Assurance", 35 | 36 | ], 37 | ) 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Must-typing 2 | 3 | Force you (or your user) annotate function type hints. 4 | 5 | **Notice: It's more like a joke, use it carefully.** 6 | 7 | **If you call `must_typing` in your module, all your user will be affected.** 8 | 9 | 10 | ## Requirement 11 | 12 | + Python3.6+ 13 | 14 | ## Usage 15 | 16 | ```python 17 | from musttyping import must_typing 18 | 19 | # Your code 20 | 21 | must_typing() 22 | ``` 23 | 24 | once a function lack of annotation... 25 | 26 | ``` 27 | Function 'f' located in test.py at line 4 28 | >> def f(): 29 | def f(): 30 | ... 31 | ... 32 | 33 | >> It lack of Return type annotation << 34 | Traceback (most recent call last): 35 | File "test.py", line 11, in 36 | musttyping.must_typing() 37 | File "musttyping\__init__.py", line 23, in must_typing 38 | raise LackAnnotationException(f"{obj} need type annotation(s)") 39 | musttyping.LackAnnotationException: need type annotation(s) 40 | ``` 41 | 42 | ## Under the hood 43 | 44 | `must_typing` will scan all function objects in current runtime, and pick out those defined by user. 45 | 46 | Then, it will check if the function lack of annotation, and raise an exception. 47 | 48 | It will only scan functions defined by user, which means all function in other module would be ignored, including Python 49 | builtin modules and 3rd party modules. 50 | 51 | Once `must_typing` detect running in debugger, it would be turned off automatically. 52 | 53 | ### detect targets 54 | 55 | + user defined functions 56 | + user defined class methods 57 | 58 | ### non detect targets 59 | 60 | + builtin and 3rd party module functions 61 | + functions written in C 62 | + lambda functions 63 | + functions defined in closure 64 | + functions defined in other thread (coming soon) 65 | + return annotation in class magic methods 66 | 67 | ## Why this package 68 | 69 | Just for fun. 70 | 71 | It's better to use `--disallow-untyped-calls` in *mypy* or some other equivalents. 72 | 73 | ## License 74 | 75 | MIT 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # IDEs 132 | .vscode/ 133 | .idea/ -------------------------------------------------------------------------------- /musttyping/core.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | from pathlib import Path 3 | from sys import base_exec_prefix, base_prefix, exec_prefix, gettrace, intern, prefix 4 | from types import FunctionType 5 | from typing import Any, List, Optional 6 | 7 | from _sitebuiltins import Quitter 8 | 9 | _always_ignore: bool = False 10 | _libs_root_paths: List[Path] = [Path(x) for x in (prefix, base_prefix, exec_prefix, base_exec_prefix)] 11 | 12 | _lambda_string: str = intern("") 13 | _main_string: str = intern("__main__") 14 | _spec_string: str = intern("__spec__") 15 | _return_string: str = intern("return") 16 | _double_underline_string: str = intern("__") 17 | 18 | # we won't detect if it needs annotation running in debugger (or some other tracing environments) 19 | if gettrace() or not isinstance(exit, Quitter): 20 | _always_ignore = True 21 | 22 | 23 | class LackType(Enum): 24 | Argument = auto() 25 | Return = auto() 26 | 27 | 28 | def need_func_typing(f: FunctionType) -> Optional[LackType]: 29 | name = f.__name__ 30 | code = f.__code__ 31 | args = code.co_varnames[: code.co_argcount] 32 | annotations = f.__annotations__ 33 | is_method = f.__name__ != f.__qualname__ 34 | 35 | # as a method, skip 'self' and 'cls' 36 | if is_method: 37 | args = args[1:] 38 | 39 | for arg in args: 40 | if arg not in annotations: 41 | return LackType.Argument 42 | 43 | # magic method needn't return annotation 44 | if is_method and name[:2] == name[-2:] == _double_underline_string: 45 | return None 46 | else: 47 | return LackType.Return if _return_string not in annotations else None 48 | 49 | 50 | def need_typing(f: Any) -> Optional[LackType]: 51 | if _always_ignore: 52 | return None 53 | 54 | # only focus on functions written in Python 55 | if not isinstance(f, FunctionType): 56 | return None 57 | 58 | # make type hint for lambda ? 59 | if f.__name__ == _lambda_string: 60 | return None 61 | 62 | # it's bad to annotate a closure 63 | if f.__closure__: 64 | return None 65 | 66 | # main module has no module spec 67 | if f.__module__ == _main_string: 68 | return need_func_typing(f) 69 | 70 | module_spec = f.__globals__.get(_spec_string, None) 71 | if not module_spec: 72 | return None 73 | 74 | if not module_spec.has_location: 75 | return None 76 | 77 | module_path = Path(module_spec.origin).absolute() 78 | # ignore builtin and 3rd party modules 79 | if any(module_path.is_relative_to(p) for p in _libs_root_paths): 80 | return None 81 | 82 | return need_func_typing(f) 83 | --------------------------------------------------------------------------------