righttyper 0.0.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
@@ -0,0 +1 @@
1
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.1
2
+ Name: righttyper
3
+ Version: 0.0.5
4
+ Summary: A fast runtime type hint assistant for Python code.
5
+ Author-email: Emery Berger <emerydb@amazon.com>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Requires-Dist: libcst==1.2.0
14
+ Requires-Dist: click>=8.1.7
15
+ Requires-Dist: numpy>=1.26.4
16
+ Requires-Dist: pandas>=2.2.0
17
+ Requires-Dist: torch>=2.3.1
18
+ Requires-Dist: rich>=13.7.1
19
+ Requires-Dist: runstats>=2.0.0
20
+ Requires-Dist: scipy>=1.12.0
21
+ Requires-Dist: boto3>=1.34.68
22
+
23
+ # RightTyper
24
+
25
+ RightTyper is a Python tool that generates types for your function
26
+ arguments and return values. It is inspired by and produces much the
27
+ same results as Instagram's `monkeytype`. At the same time,
28
+ RightTyper's approach ends up being more flexible and up to fifty
29
+ times faster. RightTyper lets your code run at nearly full speed with
30
+ almost no memory overhead. As a result, you won't experience slow
31
+ downs in your code or large memory consumption while using it,
32
+ allowing you to integrate it with your standard tests and development
33
+ process.
34
+
35
+ You can run RightTyper with arbitrary Python programs and it will generate
36
+ types for every function that gets executed. It works great in combination with PyTest:
37
+
38
+ ```bash
39
+ python3 -m righttyper -m pytest --continue-on-collection-errors /your/test/dir
40
+ ```
41
+
42
+ In addition to generating types, RightTyper has the following features:
43
+
44
+ * Efficiently computes type annotation "coverage" for a file or directory of files
45
+ * Infers shape annotations for NumPy/JAX/PyTorch tensors, compatible with `jaxtyping` and `beartype` or `typeguard`.
46
+
47
+
48
+ ## Installation
49
+
50
+ To install the latest version of RightTyper from its repository,
51
+ just use `pip` as shown below:
52
+
53
+ ```bash
54
+ python3 -m pip install git+https://github.com/RightTyper/righttyper
55
+ ```
56
+
57
+
58
+ ## Usage
59
+
60
+ To use RightTyper, simply run your script with `righttyper` instead of `python3`:
61
+
62
+ ```bash
63
+ righttyper your_script.py [args...]
64
+ ```
65
+
66
+ This will execute `your_script.py` with RightTyper's monitoring
67
+ enabled. The type signatures of all functions will be recorded and
68
+ output to a file named `righttyper.out`. The file contains, for every
69
+ function, the signature, and a diff of the original function with the
70
+ annotated version. It also generates `jaxtyping`-compatible shape
71
+ annotations for NumPy/JAX/PyTorch tensors. Below is an example:
72
+
73
+ ```diff
74
+ test-hints.py:
75
+ ==============
76
+
77
+ def barnacle(x: numpy.ndarray) -> numpy.ndarray: ...
78
+
79
+ - def barnacle(x):
80
+ + def barnacle(x: numpy.ndarray) -> numpy.ndarray:
81
+
82
+ # Shape annoations
83
+ @beartype
84
+ def barnacle(x: Float[numpy.ndarray, "10 dim0"]) -> Float[numpy.ndarray, "dim0"]: ...
85
+
86
+ def fooq(x: int, y: str) -> bool: ...
87
+
88
+ - def fooq(x: int, y) -> bool:
89
+ + def fooq(x: int, y: str) -> bool:
90
+ ? +++++
91
+ ```
92
+
93
+ Below is the full list of options:
94
+
95
+ ```bash
96
+ Usage: python -m righttyper [OPTIONS] [SCRIPT] [ARGS]...
97
+
98
+ RightTyper efficiently generates types for your function arguments and
99
+ return values.
100
+
101
+ Options:
102
+ --all-files Process any files encountered, including in
103
+ libraries (except for those specified in
104
+ --include-files)
105
+ --include-files TEXT Include only files matching the given regex
106
+ pattern.
107
+ --srcdir DIRECTORY Use this as the base for imports.
108
+ --overwrite / --no-overwrite Overwrite files with type information.
109
+ [default: no-overwrite]
110
+ --ignore-annotations Ignore existing annotations and overwrite
111
+ with type information.
112
+ -m, --module Run the script as a module.
113
+ --verbose Print diagnostic information.
114
+ --insert-imports Insert import statements for missing classes
115
+ (MAY LEAD TO CIRCULAR IMPORTS).
116
+ --generate-stubs Generate stub files (.pyi).
117
+ --type-coverage-by-directory DIRECTORY
118
+ Report per-directory type annotation
119
+ coverage for all Python files in a directory
120
+ and its children.
121
+ --type-coverage-by-file DIRECTORY
122
+ Report per-file type annotation coverage for
123
+ all Python files in a directory or its
124
+ children.
125
+ --type-coverage-summary DIRECTORY
126
+ Report uncovered and partially covered files
127
+ and functions when performing type
128
+ annotation coverage analysis.
129
+ --version Show the version and exit.
130
+ --help Show this message and exit.
131
+ ```
132
+
133
+ ## `righttyper`: high performance
134
+
135
+ In the below example drawn from the pyperformance benchmark suite,
136
+ `monkeytype` runs 40x slower than the original program or when
137
+ running with `righttyper` (which runs under 3% slower).
138
+
139
+ ```bash
140
+ % python3 bm_mdp
141
+ Time elapsed: 6.106977417017333
142
+ % righttyper bm_mdp
143
+ Time elapsed: 6.299191833997611
144
+ % monkeytype run bm_mdp
145
+ Time elapsed: 184.57902495900635
146
+ # actual time elapsed was 275 seconds, spent post-processing
147
+ ```
148
+
149
+ # `righttyper`: low memory consumption
150
+
151
+ With `monkeytype`, this program also consumes 5GB of RAM; the original
152
+ consumes just 21MB. That's an over **200x** increase in memory
153
+ consumption. `monkeytype` also leaves behind a 3GB SQLite file.
154
+
155
+ By contrast, `righttyper`'s memory consumption is just a small
156
+ increment over the original program: it consumes about 24MB, just 15%
157
+ more.
158
+
159
+ _NOTE: this is an alpha release and should not be considered production ready._
160
+
161
+ ## Requirements
162
+
163
+ - Python 3.12 or higher
164
+
165
+ ## How it works
166
+
167
+ Monkeytype is slow because it uses Python's `setprofile` functionality
168
+ to track every single function call and return, gathers types for all
169
+ arguments and the return value, and then writes these into a SQLite
170
+ database.
171
+
172
+ By contrast, RightTyper leverages Python 3.12's new `sys.monitoring`
173
+ mechanism to allow it to add and remove type checking. It always
174
+ checks the very first invocation and exit of every function. As long
175
+ as instrumentation overhead remains below a threshold, it continues to
176
+ track functions. When necessary to reduce overhead, it selectively
177
+ de-instruments functions that have already been sampled many times. It
178
+ re-enables monitoring periodically with decreasing frequency.
@@ -0,0 +1,156 @@
1
+ # RightTyper
2
+
3
+ RightTyper is a Python tool that generates types for your function
4
+ arguments and return values. It is inspired by and produces much the
5
+ same results as Instagram's `monkeytype`. At the same time,
6
+ RightTyper's approach ends up being more flexible and up to fifty
7
+ times faster. RightTyper lets your code run at nearly full speed with
8
+ almost no memory overhead. As a result, you won't experience slow
9
+ downs in your code or large memory consumption while using it,
10
+ allowing you to integrate it with your standard tests and development
11
+ process.
12
+
13
+ You can run RightTyper with arbitrary Python programs and it will generate
14
+ types for every function that gets executed. It works great in combination with PyTest:
15
+
16
+ ```bash
17
+ python3 -m righttyper -m pytest --continue-on-collection-errors /your/test/dir
18
+ ```
19
+
20
+ In addition to generating types, RightTyper has the following features:
21
+
22
+ * Efficiently computes type annotation "coverage" for a file or directory of files
23
+ * Infers shape annotations for NumPy/JAX/PyTorch tensors, compatible with `jaxtyping` and `beartype` or `typeguard`.
24
+
25
+
26
+ ## Installation
27
+
28
+ To install the latest version of RightTyper from its repository,
29
+ just use `pip` as shown below:
30
+
31
+ ```bash
32
+ python3 -m pip install git+https://github.com/RightTyper/righttyper
33
+ ```
34
+
35
+
36
+ ## Usage
37
+
38
+ To use RightTyper, simply run your script with `righttyper` instead of `python3`:
39
+
40
+ ```bash
41
+ righttyper your_script.py [args...]
42
+ ```
43
+
44
+ This will execute `your_script.py` with RightTyper's monitoring
45
+ enabled. The type signatures of all functions will be recorded and
46
+ output to a file named `righttyper.out`. The file contains, for every
47
+ function, the signature, and a diff of the original function with the
48
+ annotated version. It also generates `jaxtyping`-compatible shape
49
+ annotations for NumPy/JAX/PyTorch tensors. Below is an example:
50
+
51
+ ```diff
52
+ test-hints.py:
53
+ ==============
54
+
55
+ def barnacle(x: numpy.ndarray) -> numpy.ndarray: ...
56
+
57
+ - def barnacle(x):
58
+ + def barnacle(x: numpy.ndarray) -> numpy.ndarray:
59
+
60
+ # Shape annoations
61
+ @beartype
62
+ def barnacle(x: Float[numpy.ndarray, "10 dim0"]) -> Float[numpy.ndarray, "dim0"]: ...
63
+
64
+ def fooq(x: int, y: str) -> bool: ...
65
+
66
+ - def fooq(x: int, y) -> bool:
67
+ + def fooq(x: int, y: str) -> bool:
68
+ ? +++++
69
+ ```
70
+
71
+ Below is the full list of options:
72
+
73
+ ```bash
74
+ Usage: python -m righttyper [OPTIONS] [SCRIPT] [ARGS]...
75
+
76
+ RightTyper efficiently generates types for your function arguments and
77
+ return values.
78
+
79
+ Options:
80
+ --all-files Process any files encountered, including in
81
+ libraries (except for those specified in
82
+ --include-files)
83
+ --include-files TEXT Include only files matching the given regex
84
+ pattern.
85
+ --srcdir DIRECTORY Use this as the base for imports.
86
+ --overwrite / --no-overwrite Overwrite files with type information.
87
+ [default: no-overwrite]
88
+ --ignore-annotations Ignore existing annotations and overwrite
89
+ with type information.
90
+ -m, --module Run the script as a module.
91
+ --verbose Print diagnostic information.
92
+ --insert-imports Insert import statements for missing classes
93
+ (MAY LEAD TO CIRCULAR IMPORTS).
94
+ --generate-stubs Generate stub files (.pyi).
95
+ --type-coverage-by-directory DIRECTORY
96
+ Report per-directory type annotation
97
+ coverage for all Python files in a directory
98
+ and its children.
99
+ --type-coverage-by-file DIRECTORY
100
+ Report per-file type annotation coverage for
101
+ all Python files in a directory or its
102
+ children.
103
+ --type-coverage-summary DIRECTORY
104
+ Report uncovered and partially covered files
105
+ and functions when performing type
106
+ annotation coverage analysis.
107
+ --version Show the version and exit.
108
+ --help Show this message and exit.
109
+ ```
110
+
111
+ ## `righttyper`: high performance
112
+
113
+ In the below example drawn from the pyperformance benchmark suite,
114
+ `monkeytype` runs 40x slower than the original program or when
115
+ running with `righttyper` (which runs under 3% slower).
116
+
117
+ ```bash
118
+ % python3 bm_mdp
119
+ Time elapsed: 6.106977417017333
120
+ % righttyper bm_mdp
121
+ Time elapsed: 6.299191833997611
122
+ % monkeytype run bm_mdp
123
+ Time elapsed: 184.57902495900635
124
+ # actual time elapsed was 275 seconds, spent post-processing
125
+ ```
126
+
127
+ # `righttyper`: low memory consumption
128
+
129
+ With `monkeytype`, this program also consumes 5GB of RAM; the original
130
+ consumes just 21MB. That's an over **200x** increase in memory
131
+ consumption. `monkeytype` also leaves behind a 3GB SQLite file.
132
+
133
+ By contrast, `righttyper`'s memory consumption is just a small
134
+ increment over the original program: it consumes about 24MB, just 15%
135
+ more.
136
+
137
+ _NOTE: this is an alpha release and should not be considered production ready._
138
+
139
+ ## Requirements
140
+
141
+ - Python 3.12 or higher
142
+
143
+ ## How it works
144
+
145
+ Monkeytype is slow because it uses Python's `setprofile` functionality
146
+ to track every single function call and return, gathers types for all
147
+ arguments and the return value, and then writes these into a SQLite
148
+ database.
149
+
150
+ By contrast, RightTyper leverages Python 3.12's new `sys.monitoring`
151
+ mechanism to allow it to add and remove type checking. It always
152
+ checks the very first invocation and exit of every function. As long
153
+ as instrumentation overhead remains below a threshold, it continues to
154
+ track functions. When necessary to reduce overhead, it selectively
155
+ de-instruments functions that have already been sampled many times. It
156
+ re-enables monitoring periodically with decreasing frequency.
@@ -0,0 +1,61 @@
1
+ [tool.black]
2
+ line-length = 100
3
+
4
+ [tool.isort]
5
+ known_first_party = ["righttyper"]
6
+
7
+ # required for compatibility with black:
8
+ profile = "black"
9
+
10
+ # To maintain consistency with other settings
11
+ line_length = 100
12
+
13
+ [tool.mypy]
14
+ # See https://mypy.readthedocs.io/en/latest/config_file.html for more mypy options.
15
+
16
+ # Enables the type-checker on the interior of functions without type annotations.
17
+ check_untyped_defs = true
18
+
19
+ # Displaying specific error codes makes it easier to silence specific errors
20
+ # See also https://mypy.readthedocs.io/en/latest/error_codes.html
21
+ show_error_codes = true
22
+
23
+ # Show source code snippets and location markers in error messages
24
+ pretty = true
25
+
26
+ # Suppresses errors about packages which do not implement type-hint sharing.
27
+ # See also https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports.
28
+ ignore_missing_imports = true
29
+
30
+ [build-system]
31
+ requires = ["setuptools>=61.0"]
32
+ build-backend = "setuptools.build_meta"
33
+
34
+ [project]
35
+ name = "righttyper"
36
+ version = "0.0.5"
37
+ authors = [
38
+ { name="Emery Berger", email="emerydb@amazon.com" },
39
+ ]
40
+ dependencies = [ "libcst==1.2.0",
41
+ "click>=8.1.7",
42
+ "numpy >= 1.26.4",
43
+ "pandas >= 2.2.0",
44
+ "torch >= 2.3.1",
45
+ "rich >= 13.7.1",
46
+ "runstats>=2.0.0",
47
+ "scipy>=1.12.0",
48
+ "boto3>=1.34.68",
49
+ ]
50
+ description = "A fast runtime type hint assistant for Python code."
51
+ readme = "README.md"
52
+ requires-python = ">=3.12"
53
+ classifiers = [
54
+ "Programming Language :: Python :: 3",
55
+ "License :: OSI Approved :: MIT License",
56
+ "Operating System :: OS Independent",
57
+ ]
58
+
59
+ [project.scripts]
60
+ righttyper = "righttyper.righttyper:main"
61
+
File without changes
@@ -0,0 +1,4 @@
1
+ import righttyper.righttyper
2
+
3
+ if __name__ == "__main__":
4
+ righttyper.righttyper.main()
@@ -0,0 +1,102 @@
1
+ from typing import (
2
+ Dict,
3
+ List,
4
+ Optional,
5
+ Set,
6
+ Tuple,
7
+ Union,
8
+ )
9
+
10
+ import libcst as cst
11
+
12
+ from righttyper.righttyper_types import (
13
+ ArgumentName,
14
+ Filename,
15
+ FuncInfo,
16
+ FunctionName,
17
+ Typename,
18
+ )
19
+
20
+
21
+ class AnnotateFunctionTransformer(cst.CSTTransformer):
22
+ def __init__(
23
+ self,
24
+ filename: str,
25
+ type_annotations: Dict[
26
+ FuncInfo,
27
+ Tuple[
28
+ List[Tuple[ArgumentName, Typename]],
29
+ Typename,
30
+ ],
31
+ ],
32
+ not_annotated: Dict[FuncInfo, Set[str]],
33
+ ) -> None:
34
+ self.filename = filename
35
+ self.type_annotations = type_annotations
36
+ self.not_annotated = not_annotated
37
+ self.class_name: List[str] = []
38
+
39
+ def visit_ClassDef(self, node: cst.ClassDef) -> Optional[bool]:
40
+ self.class_name.append(node.name.value)
41
+ return None
42
+
43
+ def leave_ClassDef(
44
+ self,
45
+ original_node: cst.ClassDef,
46
+ updated_node: cst.ClassDef,
47
+ ) -> Union[cst.BaseStatement, cst.RemovalSentinel]:
48
+ self.class_name.pop()
49
+ return original_node
50
+
51
+ def leave_FunctionDef(
52
+ self,
53
+ original_node: cst.FunctionDef,
54
+ updated_node: cst.FunctionDef,
55
+ ) -> cst.FunctionDef:
56
+ # real_name = ".".join(self.class_name + [original_node.name.value])
57
+ name = original_node.name.value
58
+
59
+ # TODO: the current handling will lead to a bug if a function
60
+ # appears inside and outside a class definition in the same
61
+ # file. We need to handle this case.
62
+
63
+ key = FuncInfo(
64
+ Filename(self.filename),
65
+ FunctionName(name),
66
+ ) # original_node.name.value))
67
+ if key in self.type_annotations:
68
+ args, return_type = self.type_annotations[key]
69
+ # print(f"{args=}, {return_type=}")
70
+ # Update arguments with type annotations
71
+ new_parameters = []
72
+ for parameter in updated_node.params.params:
73
+ for arg, annotation_ in args:
74
+ if parameter.name.value == arg:
75
+ if arg not in self.not_annotated[key]:
76
+ continue
77
+ parsed_annotation = cst.parse_expression(annotation_)
78
+ new_parameters.append(
79
+ parameter.with_changes(
80
+ annotation=cst.Annotation(
81
+ annotation=parsed_annotation
82
+ )
83
+ )
84
+ )
85
+ break
86
+ else:
87
+ new_parameters.append(parameter)
88
+ parsed_return_type = cst.parse_expression(return_type)
89
+ if "return" in self.not_annotated[key]:
90
+ updated_node = updated_node.with_changes(
91
+ params=updated_node.params.with_changes(
92
+ params=new_parameters
93
+ ),
94
+ returns=cst.Annotation(annotation=parsed_return_type),
95
+ )
96
+ else:
97
+ updated_node = updated_node.with_changes(
98
+ params=updated_node.params.with_changes(
99
+ params=new_parameters
100
+ ),
101
+ )
102
+ return updated_node