├── .github
├── dependabot.yml
└── workflows
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── Makefile
├── README.md
├── mypy-zope
├── mypy-zope.ini
├── setup.cfg
├── setup.py
├── src
├── mypy_zope
│ ├── __init__.py
│ └── plugin.py
└── zope-stubs
│ ├── __init__.pyi
│ ├── interface
│ ├── __init__.pyi
│ ├── _compat.pyi
│ ├── _flatten.pyi
│ ├── _zope_interface_coptimizations.pyi
│ ├── adapter.pyi
│ ├── advice.pyi
│ ├── common
│ │ ├── __init__.pyi
│ │ ├── idatetime.pyi
│ │ ├── interfaces.pyi
│ │ ├── mapping.pyi
│ │ └── sequence.pyi
│ ├── declarations.pyi
│ ├── document.pyi
│ ├── exceptions.pyi
│ ├── interface.pyi
│ ├── interfaces.pyi
│ ├── registry.pyi
│ ├── ro.pyi
│ └── verify.pyi
│ └── schema
│ ├── __init__.pyi
│ ├── _bootstrapfields.pyi
│ ├── _bootstrapinterfaces.pyi
│ ├── _compat.pyi
│ ├── _field.pyi
│ ├── _messageid.pyi
│ ├── _schema.pyi
│ ├── accessors.pyi
│ ├── fieldproperty.pyi
│ ├── interfaces.pyi
│ └── vocabulary.pyi
├── tests
├── samples
│ ├── adaptation.py
│ ├── classimplements.py
│ ├── classimplements_broken_iface.py
│ ├── classimplements_broken_impl.py
│ ├── classimplements_wrong.py
│ ├── contextmanager.py
│ ├── forward_reference_to_implementer.py
│ ├── forwardref.py
│ ├── impl_inheritance.py
│ ├── impl_property.py
│ ├── incompatible_signature.py
│ ├── innerclass.py
│ ├── interface_annotated_attribute.py
│ ├── interface_attribute.py
│ ├── interface_fieldproperty.py
│ ├── interface_getattr.py
│ ├── interface_implications.py
│ ├── interface_inheritance.py
│ ├── interface_mapping.py
│ ├── interface_meta.py
│ ├── interface_metaclass.py
│ ├── interface_self.py
│ ├── interface_unknown.py
│ ├── interface_unknown_direct.py
│ ├── interface_unknown_inherit.py
│ ├── multiple_implementer.py
│ ├── multiple_inheritance.py
│ ├── nested_definitions.py
│ ├── no_arg_method.py
│ ├── not_fully_implemented.py
│ ├── open.py
│ ├── overload.py
│ ├── overload_readme.py
│ ├── parameterized_types.py
│ ├── schema_bool.py
│ ├── schema_field_outside_inteface.py
│ ├── schema_number.py
│ ├── schema_text.py
│ ├── schema_unknown_field.py
│ ├── simple_valid.py
│ ├── unknown_interface.py
│ └── unknown_metaclass.py
└── test_samples.py
└── tox.ini
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: pip
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | open-pull-requests-limit: 10
8 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: mypy-zope
2 |
3 | on:
4 | push:
5 | branches: master
6 | pull_request:
7 |
8 | jobs:
9 | test:
10 |
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13']
15 |
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Set up Python ${{ matrix.python-version }}
19 | uses: actions/setup-python@v2
20 | with:
21 | python-version: ${{ matrix.python-version }}
22 | - name: Install dependencies
23 | run: |
24 | python -m pip install --upgrade pip
25 | pip install --upgrade -e .[test]
26 | - name: Test with pytest
27 | run: |
28 | pytest --junit-xml var/test-results/results.xml -v --cov src/mypy_zope --cov-report=term
29 | - name: Check with mypy
30 | run: |
31 | mypy src/mypy_zope --strict
32 | - name: Coveralls
33 | if: ${{ success() }}
34 | env:
35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
36 | COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN}}
37 | COVERALLS_PARALLEL: true
38 | run: |
39 | pip install coveralls
40 | coveralls --service=github
41 |
42 | report:
43 | needs: test
44 | runs-on: ubuntu-latest
45 | steps:
46 | - name: Set up Python
47 | uses: actions/setup-python@v2
48 | - name: Coveralls Finish
49 | env:
50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
51 | COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN}}
52 | run: |
53 | pip install coveralls
54 | coveralls --service=github --finish
55 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ve
2 | .mypy_cache
3 | .pytest_cache
4 | .coverage
5 | __pycache__
6 | build
7 | dist
8 | *.egg-info
9 | tags
10 | .tags
11 | *.sublime*
12 | *.swp
13 | tmp
14 | reports
15 | htmlcov
16 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file.
4 |
5 | ## 1.0.13 (unreleased)
6 | ----------------------
7 |
8 | - Nothing changed yet.
9 |
10 |
11 | ## 1.0.12 (2025-06-03)
12 | ----------------------
13 |
14 | - Support mypy-1.16
15 |
16 |
17 | ## 1.0.11 (2025-02-19)
18 | ----------------------
19 |
20 | - Support mypy-1.15
21 |
22 |
23 | ## 1.0.10 (2024-12-24)
24 | ----------------------
25 |
26 | - Support mypy-1.14
27 |
28 |
29 | ## 1.0.9 (2024-11-04)
30 | ---------------------
31 |
32 | - Support mypy-1.13
33 |
34 |
35 | ## 1.0.8 (2024-10-22)
36 | ---------------------
37 |
38 | - Support mypy 1.12.x
39 |
40 |
41 | ## 1.0.7 (2024-10-11)
42 | ---------------------
43 |
44 | - Include wheel into the release
45 |
46 |
47 | ## 1.0.6 (2024-10-10)
48 | ---------------------
49 |
50 | - Support for mypy up to 1.12.x
51 | - Support for python 3.12 and 3.13
52 |
53 |
54 | ## 1.0.5 (2024-07-02)
55 | ---------------------
56 |
57 | - Support for mypy up to 1.10.x
58 |
59 |
60 | ## 1.0.4 (2024-03-12)
61 | ---------------------
62 |
63 | - Drop support for python-3.7 (follow mypy).
64 | - Support for mypy up to 1.9.x
65 |
66 |
67 | ## 1.0.3 (2023-12-26)
68 | ---------------------
69 |
70 | - Support for mypy up to 1.8.x
71 |
72 |
73 | ## 1.0.2 (2023-12-09)
74 | ---------------------
75 |
76 | - Support for mypy up to 1.7.x
77 |
78 |
79 | ## 1.0.1 (2023-08-30)
80 | ---------------------
81 |
82 | - Support for mypy up to 1.6.0
83 |
84 |
85 | ## 1.0.0 (2023-06-26)
86 | ------------------
87 |
88 | - Support mypy up to 1.5.0
89 |
90 |
91 | 0.9.1 (2023-03-24)
92 | ------------------
93 |
94 | - Follow semantic versioning in mypy version pins (#96)
95 |
96 |
97 | 0.9.0 (2023-02-10)
98 | ------------------
99 |
100 | - Upgrade to Mypy-1.0.0 (#89)
101 | - Fix caching error (Metaclass conflict) (#86)
102 |
103 |
104 | 0.3.11 (2022-09-30)
105 | -------------------
106 |
107 | - Fix "Cannot determine consistent method resolution order (MRO)" error after
108 | repeated mypy runs (#80).
109 |
110 |
111 | 0.3.10 (2022-09-27)
112 | -------------------
113 |
114 | - Upgrade to Mypy-0.981.
115 |
116 |
117 | 0.3.9 (2022-07-19)
118 | ------------------
119 |
120 | - Upgrade to Mypy-0.971.
121 |
122 |
123 | 0.3.8 (2022-06-08)
124 | ------------------
125 |
126 | - Upgrade to Mypy-0.961.
127 |
128 |
129 | 0.3.7 (2022-04-28)
130 | ------------------
131 |
132 | - Upgrade to Mypy-0.950.
133 |
134 |
135 | 0.3.6 (2022-03-15)
136 | ------------------
137 |
138 | - Upgrade to Mypy-0.941.
139 |
140 |
141 | 0.3.5 (2022-01-11)
142 | ------------------
143 |
144 | - Upgrade to Mypy-0.931.
145 |
146 |
147 | 0.3.4 (2021-12-23)
148 | ------------------
149 |
150 | - Upgrade to Mypy-0.930.
151 |
152 |
153 | 0.3.3 (2021-12-17)
154 | ------------------
155 |
156 | - Declare support for Python-3.10.
157 | - Upgrade to Mypy-0.920.
158 |
159 |
160 | 0.3.2 (2021-06-24)
161 | ------------------
162 |
163 | - Upgrade to Mypy-0.910.
164 |
165 |
166 | 0.3.1 (2021-06-11)
167 | ------------------
168 |
169 | - Upgrade to Mypy-0.902.
170 |
171 |
172 | 0.3.0 (2021-04-04)
173 | ------------------
174 |
175 | - Support for `classImplements` declarations (#40).
176 | - Support for `@overload` decorator in interfaces (#46)
177 |
178 |
179 | 0.2.13 (2021-03-23)
180 | -------------------
181 |
182 | - Fix "Cannot determine consistent method resolution order (MRO)" error (#34, #41)
183 |
184 |
185 | 0.2.12 (2021-03-13)
186 | -------------------
187 |
188 | - Better type inference for contextmanagers and open() function: do not override
189 | the default behavior for tese cases
190 | - Support interfaces defined inside classes
191 |
192 | 0.2.11 (2021-02-21)
193 | -------------------
194 |
195 | - Upgrade to Mypy-0.812.
196 |
197 |
198 | 0.2.10 (2021-01-27)
199 | -------------------
200 |
201 | - Avoid failure when handling metaclasses of unknown type (#28).
202 |
203 |
204 | 0.2.9 - 2021-01-23
205 | ------------------
206 |
207 | - Upgrade to Mypy-0.800
208 | - Add support for Python 3.9.
209 |
210 |
211 | 0.2.8 - 2020-10-09
212 | ------------------
213 |
214 | - Upgrade to Mypy-0.790
215 |
216 |
217 | 0.2.7 - 2020-06-19
218 | ------------------
219 |
220 | - Upgrade to Mypy-0.770
221 |
222 |
223 | 0.2.6 - 2020-06-02
224 | ------------------
225 |
226 | - Improved mypy annotations in Components methods
227 |
228 |
229 | 0.2.5 - 2020-03-12
230 | ------------------
231 |
232 | - Upgrade to Mypy-0.770
233 |
234 |
235 | 0.2.4 - 2019-12-30
236 | ------------------
237 |
238 | - Upgrade to Mypy-0.761
239 | - Add support for Python 3.8.
240 |
241 |
242 | 0.2.3 - 2019-11-30
243 | ------------------
244 |
245 | - Upgrade to Mypy-0.750
246 |
247 |
248 | 0.2.2 - 2019-10-28
249 | ------------------
250 |
251 | - Upgrade to Mypy-0.740
252 |
253 |
254 | 0.2.1 - 2019-09-30
255 | ------------------
256 |
257 | - Upgrade to Mypy-0.730
258 | - Fixing crash while analyzing dynamically inherited class definitions (#11)
259 |
260 |
261 | 0.2.0 - 2019-08-03
262 | ------------------
263 |
264 | - Support for Mypy-0.720.
265 | - Avoid merging interface and implementation class hierarchies into single MRO.
266 | - Implement implementation class validation against the declared interfaces.
267 |
268 | 0.1.3 - 2019-05-05
269 | ------------------
270 |
271 | - Initial release.
272 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Shoobx, Inc
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 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include *.md
2 | include LICENSE
3 | graft tests
4 | graft src/zope-stubs
5 | global-exclude __pycache__
6 | global-exclude *.py[co]
7 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | VE=ve
2 | VEBIN=$(VE)/bin
3 |
4 | all: $(VE)
5 |
6 | $(VE): setup.py
7 | python3 -m venv $(VE)
8 | $(VEBIN)/pip install -e .[test]
9 |
10 | .PHONY: test
11 | test:
12 | $(VEBIN)/pytest -v --cov src/mypy_zope --cov-report=html --cov-report=term
13 |
14 |
15 | # Mypy self-test
16 | .PHONY: mypy
17 | mypy:
18 | $(VEBIN)/mypy src/mypy_zope --strict
19 |
20 | .PHONY: mypy-report
21 | mypy-report:
22 | $(VEBIN)/mypy src/mypy_zope --strict --html-report reports/html --txt-report reports/txt
23 | cat reports/txt/index.txt
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Plugin for mypy to support zope.interface
2 |
3 | [](https://coveralls.io/github/Shoobx/mypy-zope)
4 | [](http://mypy-lang.org/)
5 |
6 | The goal is to be able to make zope interfaces to be treated as types in mypy
7 | sense.
8 |
9 | ## Usage
10 |
11 | Install both mypy and mypy-zope:
12 | ```sh
13 | pip install mypy-zope
14 | ```
15 |
16 | Edit `mypy.ini` file in your project to enable the plugin:
17 |
18 | ```ini
19 | [mypy]
20 | namespace_packages=True
21 | plugins=mypy_zope:plugin
22 | ```
23 |
24 | You're done! You can now check your project with mypy:
25 |
26 | ```sh
27 | mypy your-project-dir
28 | ```
29 |
30 | ## What is supported?
31 |
32 | You can browse
33 | [sample files](https://github.com/Shoobx/mypy-zope/tree/master/tests/samples)
34 | to get some sense on what features are supported and how they are handled.
35 |
36 | ### Interface declarations
37 |
38 | You can define the interface and provide implementation:
39 |
40 | ```python
41 | class IAnimal(zope.interface.Interface):
42 | def say() -> None:
43 | pass
44 |
45 | @zope.interface.implementer(IAnimal)
46 | class Cow(object):
47 | def say(self) -> None:
48 | print("Moooo")
49 |
50 | animal: IAnimal = Cow()
51 | animal.say()
52 | ```
53 |
54 | The interface `IAnimal` will be treated as superclass of the implementation
55 | `Cow`: you will be able to pass an implementation to functions accepting an
56 | interface and all the usual polymorphism tricks.
57 |
58 | It is also possible to declare the implementation using `classImplements`
59 | function with the same effect as `@imlementer` decorator. This is useful if
60 | you do not control the code that defines the implementation class.
61 |
62 | ```python
63 | classImplements(Cow, IAnimal)
64 |
65 | animal: IAnimal = Cow()
66 | ```
67 |
68 | ### Schema field type inference
69 | A limited support for defining attributes as `zope.schema.Field`s is supported too:
70 |
71 | ```python
72 | class IAnimal(zope.interface.Interface):
73 | number_of_legs = zope.schema.Int(title="Number of legs")
74 |
75 | @zope.interface.implementer(IAnimal)
76 | class Cow(object):
77 | number_of_legs = 4
78 | ```
79 |
80 | In context of an interface, some known `zope.schema` field types are
81 | automatically translated to python types, so the `number_of_legs` attributes is
82 | getting the type `int` in the example above. That means mypy will report an
83 | error if you try to assign string to that attribute on an instance of `IAnimal`
84 | type. Custom fields or fields not recognized by plugin are given type `Any`.
85 |
86 | ### Field properties
87 |
88 | Support for `zope.schema.FieldProperty` is limited, because type information is
89 | not transferred from an interface to implementation attribute, but mypy doesn't
90 | report errors on sources like this:
91 |
92 | ```python
93 | class IAnimal(zope.interface.Interface):
94 | number_of_legs = zope.schema.Int(title="Number of legs")
95 |
96 | @zope.interface.implementer(IAnimal)
97 | class Cow(object):
98 | number_of_legs = zope.schema.FieldProperty(IAnimal['number_of_legs'])
99 | ```
100 |
101 | The type of `Cow.number_of_legs` will become `Any` in this case, even though
102 | `IAnimal.number_of_legs` would be inferred as `int`.
103 |
104 | ### Adaptation pattern
105 |
106 | Zope interfaces can be "called" to lookup an adapter, like this:
107 |
108 | ```python
109 | class IEUPowerSocket(zope.interface.Interface):
110 | def fit():
111 | pass
112 |
113 | adapter = IEUPowerSocket(us_plug)
114 | adapter.fit()
115 | ```
116 |
117 | Type of the `adapter` variable will be set to `IEUPowerSocket`.
118 |
119 | ### Conditional type inference
120 |
121 | When using `zope.interface`'s `implementedBy()` and `providedBy()` methods
122 | in an if statement, `mypy` will know which type it is inside those statements.
123 |
124 | ```python
125 | if IAnimal.providedBy(ob):
126 | ob.number_of_legs += 2
127 |
128 | ```
129 |
130 | ### Declaration of overloaded methods in interfaces
131 |
132 | Similarly to regular [overloaded
133 | functions](https://docs.python.org/3/library/typing.html#typing.overload),
134 | `@overload` declarations are supported in interfaces as well:
135 |
136 | ```python
137 | class IAnimal(zope.interface.Interface):
138 | @overload
139 | def say() -> str:
140 | ...
141 |
142 | @overload
143 | def say(count: int) -> List[str]:
144 | ...
145 |
146 | def say(count: int = None) -> Union[str, List[str]]:
147 | pass
148 |
149 |
150 | @zope.interface.implementer(IAnimal)
151 | class Cow(object):
152 | @overload
153 | def say(self) -> str:
154 | ...
155 |
156 | @overload
157 | def say(self, count: int) -> List[str]:
158 | ...
159 |
160 | def say(self, count: int = None) -> Union[str, List[str]]:
161 | if count is None:
162 | return "Mooo"
163 | return ["Mooo"] * count
164 | ```
165 |
166 | ### Type stubs for zope.interface and zope.schema
167 |
168 | `mypy-zope` ships with type stubs (`*.pyi` files) for `zope.interface` and
169 | `zope.schema` packages. They are enabled automatically as soon as plugin is
170 | enabled.
171 |
172 |
173 | ## What is not supported?
174 |
175 | These `zope.interface` features are not supported:
176 |
177 | * Declaring modules as interface implementers.
178 | * Type inference for `zope.schema.List` and `zope.schema.Dict` fields.
179 | * Stub files are largely incomplete
180 | * Interface compatibility checker will not type-check non-method attributes
181 |
182 | ## Ready to use!
183 |
184 | Currently, the project is used in production in various substantially large
185 | projects and considered production-grade, however there still might be subtle
186 | bugs around. Suggestions and pull requests are welcomed!
187 |
188 |
--------------------------------------------------------------------------------
/mypy-zope:
--------------------------------------------------------------------------------
1 | #!/bin/sh -x
2 | ve/bin/mypy --config-file mypy-zope.ini --show-traceback $@
3 |
--------------------------------------------------------------------------------
/mypy-zope.ini:
--------------------------------------------------------------------------------
1 | [mypy]
2 | namespace_packages=True
3 | plugins=mypy_zope:plugin
4 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = mypy-zope
3 | version = 1.0.13.dev0
4 | author = Andrey Lebedev
5 | author_email = andrey.lebedev@gmail.com
6 | url = https://github.com/Shoobx/mypy-zope
7 | long_description = file: README.md
8 | long_description_content_type = text/markdown
9 | description = Plugin for mypy to support zope interfaces
10 | keywords = mypy, zope, interfaces, typing
11 | classifiers =
12 | Development Status :: 5 - Production/Stable
13 | Environment :: Console
14 | Intended Audience :: Developers
15 | Programming Language :: Python :: 3
16 | Programming Language :: Python :: 3.8
17 | Programming Language :: Python :: 3.9
18 | Programming Language :: Python :: 3.10
19 | Programming Language :: Python :: 3.11
20 | Programming Language :: Python :: 3.12
21 | Programming Language :: Python :: 3.13
22 | License :: OSI Approved :: MIT License
23 | Operating System :: OS Independent
24 | Topic :: Software Development
25 |
26 | [options]
27 | packages =
28 | mypy_zope
29 | zope-stubs
30 | zope-stubs.schema
31 | zope-stubs.interface
32 | zope-stubs.interface.common
33 | package_dir = =src
34 | install_requires =
35 | mypy>=1.0.0,<1.17.0
36 | zope.interface
37 | zope.schema
38 | include_package_data = True
39 | zip_safe = False
40 |
41 | [options.extras_require]
42 | test =
43 | pytest>=4.6
44 | pytest-cov
45 | lxml
46 |
47 | [zest.releaser]
48 | create-wheel = yes
49 |
50 | [flake8]
51 | max-line-length = 88
52 | ignore =
53 | # Black creates whitespace before colon
54 | E203
55 |
56 | [check-manifest]
57 | ignore =
58 | mypy-zope.ini
59 | mypy-zope
60 | Makefile
61 | tox.ini
62 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | setup()
3 |
--------------------------------------------------------------------------------
/src/mypy_zope/__init__.py:
--------------------------------------------------------------------------------
1 | from .plugin import plugin
--------------------------------------------------------------------------------
/src/mypy_zope/plugin.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from typing import List, Dict, Any, Callable, Optional, Tuple, Sequence, Union
3 | from typing import Type as PyType
4 | from typing import cast
5 |
6 | from mypy.types import (
7 | Type,
8 | Instance,
9 | CallableType,
10 | UnionType,
11 | NoneTyp,
12 | AnyType,
13 | TypeOfAny,
14 | PartialType,
15 | FunctionLike,
16 | )
17 | from mypy.checker import TypeChecker, is_false_literal
18 | from mypy.options import Options
19 | from mypy.nodes import TypeInfo
20 | from mypy.plugin import (
21 | CheckerPluginInterface,
22 | SemanticAnalyzerPluginInterface,
23 | MethodSigContext,
24 | Plugin,
25 | AnalyzeTypeContext,
26 | FunctionContext,
27 | MethodContext,
28 | AttributeContext,
29 | ClassDefContext,
30 | )
31 | from mypy.subtypes import find_member
32 | from mypy.plugins.default import DefaultPlugin
33 |
34 | from mypy.nodes import (
35 | Context,
36 | Var,
37 | Argument,
38 | FuncDef,
39 | OverloadedFuncDef,
40 | Decorator,
41 | CallExpr,
42 | RefExpr,
43 | Expression,
44 | ClassDef,
45 | Statement,
46 | Block,
47 | IndexExpr,
48 | MemberExpr,
49 | SymbolTable,
50 | SymbolTableNode,
51 | MDEF,
52 | ARG_POS,
53 | ARG_OPT,
54 | FUNC_NO_INFO,
55 | NameExpr,
56 | MypyFile,
57 | SymbolNode,
58 | )
59 |
60 | from collections import defaultdict
61 |
62 |
63 | def make_simple_type(
64 | fieldtype: str,
65 | arg_names: List[List[Optional[str]]],
66 | args: List[List[Expression]],
67 | api: CheckerPluginInterface,
68 | ) -> Optional[Type]:
69 | typename = SIMPLE_FIELD_TO_TYPE.get(fieldtype)
70 | if not typename:
71 | return None
72 | stdtype = api.named_generic_type(typename, [])
73 | for nameset, argset in zip(arg_names, args):
74 | for name, arg in zip(nameset, argset):
75 | if name == "required" and is_false_literal(arg):
76 | nonetype = NoneTyp()
77 | optionaltype = UnionType([stdtype, nonetype])
78 | return optionaltype
79 | return stdtype
80 |
81 |
82 | FIELD_TO_TYPE_MAKER = {
83 | "zope.schema._bootstrapfields.Text": make_simple_type,
84 | "zope.schema._bootstrapfields.Bool": make_simple_type,
85 | "zope.schema._bootstrapfields.Complex": make_simple_type,
86 | "zope.schema._bootstrapfields.Real": make_simple_type,
87 | "zope.schema._bootstrapfields.Int": make_simple_type,
88 | }
89 |
90 | SIMPLE_FIELD_TO_TYPE = {
91 | "zope.schema._bootstrapfields.Text": "str",
92 | "zope.schema._bootstrapfields.Bool": "bool",
93 | "zope.schema._bootstrapfields.Complex": "complex",
94 | "zope.schema._bootstrapfields.Real": "float",
95 | "zope.schema._bootstrapfields.Int": "int",
96 | }
97 |
98 |
99 | HACK_IS_ABSTRACT_NON_PROPAGATING = -12345678
100 |
101 |
102 | class ZopeInterfacePlugin(Plugin):
103 | def __init__(self, options: Options):
104 | super().__init__(options)
105 | self.fallback = DefaultPlugin(options)
106 |
107 | def log(self, msg: str) -> None:
108 | if self.options.verbosity >= 1:
109 | print("ZOPE:", msg, file=sys.stderr)
110 |
111 | def get_type_analyze_hook(
112 | self, fullname: str
113 | ) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
114 | # print(f"get_type_analyze_hook: {fullname}")
115 | return None
116 |
117 | def get_function_hook(
118 | self, fullname: str
119 | ) -> Optional[Callable[[FunctionContext], Type]]:
120 | # print(f"get_function_hook: {fullname}")
121 |
122 | def analyze(function_ctx: FunctionContext) -> Type:
123 | # strtype = function_ctx.api.named_generic_type('builtins.str', [])
124 | # optstr = function_ctx.api.named_generic_type('typing.Optional', [strtype])
125 | api = function_ctx.api
126 | deftype = function_ctx.default_return_type
127 |
128 | if self._is_subclass(deftype, "zope.interface.interface.Attribute"):
129 | return self._get_schema_field_type(
130 | deftype, function_ctx.arg_names, function_ctx.args, api
131 | )
132 | if self._is_subclass(deftype, "zope.schema.fieldproperty.FieldProperty"):
133 | # We cannot accurately determine the type, fallback to Any
134 | return AnyType(TypeOfAny.implementation_artifact)
135 |
136 | return deftype
137 |
138 | def class_implements_hook(function_ctx: FunctionContext) -> Type:
139 | assert len(function_ctx.arg_types) == 2
140 | arg_impl = function_ctx.arg_types[0][0]
141 | expr = function_ctx.args[0][0]
142 | implname = expr.fullname if isinstance(expr, NameExpr) else "expression"
143 | if not isinstance(arg_impl, CallableType):
144 | function_ctx.api.fail(
145 | f"{implname} is not a class, "
146 | "cannot mark it as a interface implementation",
147 | function_ctx.context,
148 | )
149 | return function_ctx.default_return_type
150 | assert isinstance(arg_impl, CallableType)
151 | impl_type = arg_impl.ret_type
152 | assert isinstance(impl_type, Instance)
153 |
154 | for expr, arg_iface in zip(function_ctx.args[1], function_ctx.arg_types[1]):
155 | exprname = expr.fullname if isinstance(expr, NameExpr) else "expression"
156 | if not isinstance(arg_iface, CallableType):
157 | function_ctx.api.fail(
158 | f"{exprname} is not a class, "
159 | f"cannot mark {implname} as an implementation of "
160 | f"{exprname}",
161 | function_ctx.context,
162 | )
163 | continue
164 |
165 | iface_type = arg_iface.ret_type
166 | assert isinstance(iface_type, Instance)
167 | if not self._is_interface(iface_type.type):
168 | function_ctx.api.fail(
169 | f"{exprname} is not an interface", function_ctx.context,
170 | )
171 | function_ctx.api.fail(
172 | f"Make sure you have stubs for all packages that "
173 | f"provide interfaces for {exprname} class hierarchy.",
174 | function_ctx.context,
175 | )
176 | continue
177 |
178 | self._apply_interface(impl_type.type, iface_type.type)
179 | self._report_implementation_problems(
180 | impl_type, iface_type, function_ctx.api, function_ctx.context
181 | )
182 |
183 | return function_ctx.default_return_type
184 |
185 | if fullname == "zope.interface.declarations.classImplements":
186 | return class_implements_hook
187 |
188 | # Give preference to deault plugin
189 | hook = self.fallback.get_function_hook(fullname)
190 | if hook is not None:
191 | return hook
192 | return analyze
193 |
194 | def get_method_signature_hook(
195 | self, fullname: str
196 | ) -> Optional[Callable[[MethodSigContext], CallableType]]:
197 | # print(f"get_method_signature_hook: {fullname}")
198 | return None
199 |
200 | def get_method_hook(
201 | self, fullname: str
202 | ) -> Optional[Callable[[MethodContext], Type]]:
203 | # print(f"get_method_hook: {fullname}")
204 |
205 | methodname = fullname.split(".")[-1]
206 | if methodname in ("providedBy", "implementedBy"):
207 |
208 | def analyze(method_ctx: MethodContext) -> Type:
209 | assert isinstance(method_ctx.context, CallExpr)
210 | assert isinstance(method_ctx.context.callee, MemberExpr)
211 | if method_ctx.context.callee.name == "providedBy":
212 | method_ctx.context.callee.fullname = "builtins.isinstance"
213 | else:
214 | method_ctx.context.callee.fullname = "builtins.issubclass"
215 | method_ctx.context.args = [
216 | method_ctx.args[0][0],
217 | method_ctx.context.callee.expr,
218 | ]
219 |
220 | return method_ctx.default_return_type
221 |
222 | return analyze
223 |
224 | def analyze_implementation(method_ctx: MethodContext) -> Type:
225 | deftype = method_ctx.default_return_type
226 | if not isinstance(method_ctx.context, ClassDef):
227 | return deftype
228 |
229 | impl_info = method_ctx.context.info
230 | if impl_info is FUNC_NO_INFO:
231 | return deftype
232 |
233 | impl_type = Instance(impl_info, [])
234 | md = self._get_metadata(impl_info)
235 | ifaces = cast(List[str], md.get("implements", []))
236 | for ifacename in ifaces:
237 | # iface_type = method_ctx.api.named_generic_type(ifacename, [])
238 | assert isinstance(method_ctx.api, TypeChecker)
239 | iface_type = self._lookup_type(ifacename, method_ctx.api)
240 | self._report_implementation_problems(
241 | impl_type, iface_type, method_ctx.api, method_ctx.context
242 | )
243 | return deftype
244 |
245 | if fullname == "zope.interface.declarations.implementer.__call__":
246 | return analyze_implementation
247 |
248 | return None
249 |
250 | def get_attribute_hook(
251 | self, fullname: str
252 | ) -> Optional[Callable[[AttributeContext], Type]]:
253 | # print(f"get_attribute_hook: {fullname}")
254 | return None
255 |
256 | def get_class_decorator_hook(
257 | self, fullname: str
258 | ) -> Optional[Callable[[ClassDefContext], None]]:
259 | # print(f"get_class_decorator_hook: {fullname}")
260 |
261 | def apply_implementer(
262 | iface_arg: Expression,
263 | class_info: TypeInfo,
264 | api: SemanticAnalyzerPluginInterface,
265 | ) -> None:
266 | if not isinstance(iface_arg, RefExpr):
267 | api.fail(
268 | "Argument to implementer should be a ref expression", iface_arg
269 | )
270 | return
271 | iface_name = iface_arg.fullname
272 | if iface_name is None:
273 | # unknown interface, probably from stubless package
274 | return
275 |
276 | iface_type = iface_arg.node
277 | if iface_type is None:
278 | return
279 | if not isinstance(iface_type, TypeInfo):
280 | # Possibly an interface from unimported package, ignore
281 | return
282 |
283 | if not self._is_interface(iface_type):
284 | api.fail(
285 | f"zope.interface.implementer accepts interface, "
286 | f"not {iface_name}.",
287 | iface_arg,
288 | )
289 | api.fail(
290 | f"Make sure you have stubs for all packages that "
291 | f"provide interfaces for {iface_name} class hierarchy.",
292 | iface_arg,
293 | )
294 | return
295 |
296 | self._apply_interface(class_info, iface_type)
297 |
298 | def analyze(classdef_ctx: ClassDefContext) -> None:
299 | api = classdef_ctx.api
300 |
301 | decor = cast(CallExpr, classdef_ctx.reason)
302 |
303 | for iface_arg in decor.args:
304 | apply_implementer(iface_arg, classdef_ctx.cls.info, api)
305 |
306 | if fullname == "zope.interface.declarations.implementer":
307 | return analyze
308 | return None
309 |
310 | def get_metaclass_hook(
311 | self, fullname: str
312 | ) -> Optional[Callable[[ClassDefContext], None]]:
313 | # print(f"get_metaclass_hook: {fullname}")
314 | def analyze_metaclass(ctx: ClassDefContext) -> None:
315 | metaclass = ctx.cls.metaclass
316 | if not isinstance(metaclass, RefExpr):
317 | return
318 | info = metaclass.node
319 | if not isinstance(info, TypeInfo):
320 | return
321 |
322 | expected = "zope.interface.interface.InterfaceClass"
323 | if any(node.fullname == expected for node in info.mro):
324 | self.log(f"Found zope interface: {ctx.cls.fullname}")
325 | md = self._get_metadata(ctx.cls.info)
326 | md["is_interface"] = True
327 |
328 | return analyze_metaclass
329 |
330 | def get_base_class_hook(
331 | self, fullname: str
332 | ) -> Optional[Callable[[ClassDefContext], None]]:
333 | # print(f"get_base_class_hook: {fullname}")
334 | def analyze_subinterface(classdef_ctx: ClassDefContext) -> None:
335 | # If one of the bases is an interface, this is also an interface
336 | if isinstance(classdef_ctx.reason, IndexExpr):
337 | # Generic parameterised interface
338 | reason = classdef_ctx.reason.base
339 | else:
340 | reason = classdef_ctx.reason
341 | if not isinstance(reason, RefExpr):
342 | return
343 | cls_info = classdef_ctx.cls.info
344 |
345 | api = classdef_ctx.api
346 | base_name = reason.fullname
347 | if not base_name:
348 | return
349 | if "." not in base_name:
350 | # When class is inherited from a dynamic parameter, it will not
351 | # have a fully-qualified name, so we cannot use api to look it
352 | # up. Just give up in this case.
353 | return
354 | base_node = api.lookup_fully_qualified_or_none(base_name)
355 | if not base_node:
356 | return
357 | if not isinstance(base_node.node, TypeInfo):
358 | return
359 |
360 | if self._is_interface(base_node.node):
361 | self.log(f"Found zope subinterface: {cls_info.fullname}")
362 | cls_md = self._get_metadata(cls_info)
363 | cls_md["is_interface"] = True
364 |
365 | return analyze_subinterface
366 |
367 | def get_customize_class_mro_hook(
368 | self, fullname: str
369 | ) -> Optional[Callable[[ClassDefContext], None]]:
370 | # print(f"get_customize_class_mro_hook: {fullname}")
371 |
372 | def analyze_interface_base(classdef_ctx: ClassDefContext) -> None:
373 | # Create fake constructor to mimic adaptation signature
374 | info = classdef_ctx.cls.info
375 | api = classdef_ctx.api
376 | if "__init__" in info.names:
377 | # already patched
378 | return
379 |
380 | # Create a method:
381 | #
382 | # def __init__(self, obj, alternate=None) -> None
383 | #
384 | # This will make interfaces
385 | selftp = Instance(info, [])
386 | anytp = AnyType(TypeOfAny.implementation_artifact)
387 | init_fn = CallableType(
388 | arg_types=[selftp, anytp, anytp],
389 | arg_kinds=[ARG_POS, ARG_POS, ARG_OPT],
390 | arg_names=["self", "obj", "alternate"],
391 | ret_type=NoneTyp(),
392 | fallback=api.named_type("builtins.function"),
393 | )
394 | newinit = FuncDef("__init__", [], Block([]), init_fn)
395 | newinit.info = info
396 | info.names["__init__"] = SymbolTableNode(
397 | MDEF, newinit, plugin_generated=True
398 | )
399 |
400 | def analyze(classdef_ctx: ClassDefContext) -> None:
401 | info = classdef_ctx.cls.info
402 |
403 | # If we are dealing with an interface, massage it a bit, e.g.
404 | # inject `self` argument to all methods
405 | directiface = "zope.interface.interface.Interface" in [
406 | b.type.fullname for b in info.bases
407 | ]
408 | subinterface = any(self._is_interface(b.type) for b in info.bases)
409 | if directiface or subinterface:
410 | self._analyze_zope_interface(classdef_ctx.api, classdef_ctx.cls)
411 |
412 | if fullname == "zope.interface.interface.Interface":
413 | return analyze_interface_base
414 |
415 | return analyze
416 |
417 | def _is_subclass(self, typ: Type, classname: str) -> bool:
418 | if not isinstance(typ, Instance):
419 | return False
420 |
421 | parent_names = [t.fullname for t in typ.type.mro]
422 | return classname in parent_names
423 |
424 | def _get_schema_field_type(
425 | self,
426 | typ: Type,
427 | arg_names: List[List[Optional[str]]],
428 | args: List[List[Expression]],
429 | api: CheckerPluginInterface,
430 | ) -> Type:
431 | """Given subclass of zope.interface.Attribute, determine python
432 | type that would correspond to it.
433 | """
434 | # If we are not processing an interface, leave the type as is
435 | assert isinstance(api, TypeChecker)
436 | scopecls = api.scope.active_class()
437 | if scopecls is None:
438 | return typ
439 |
440 | if not self._is_interface(scopecls):
441 | return typ
442 |
443 | # If default type is a zope.schema.Field, we should convert it to a
444 | # python type
445 | if not isinstance(typ, Instance):
446 | return typ
447 |
448 | parent_names = [t.fullname for t in typ.type.mro]
449 |
450 | # If it is a konwn field, build a python type out of it
451 | for clsname in parent_names:
452 | maker = FIELD_TO_TYPE_MAKER.get(clsname)
453 | if maker is None:
454 | continue
455 |
456 | convtype = maker(clsname, arg_names, args, api)
457 | if convtype:
458 | self.log(
459 | f"Converting a field {typ} into type {convtype} "
460 | f"for {scopecls.fullname}"
461 | )
462 | return convtype
463 |
464 | # For unknown fields, just return ANY
465 | self.log(f"Unknown field {typ} in interface {scopecls.fullname}")
466 | return AnyType(
467 | TypeOfAny.implementation_artifact, line=typ.line, column=typ.column
468 | )
469 |
470 | def _analyze_zope_interface(
471 | self, api: SemanticAnalyzerPluginInterface, cls: ClassDef
472 | ) -> None:
473 | self.log(f"Adjusting zope interface: {cls.info.fullname}")
474 | md = self._get_metadata(cls.info)
475 | # Even though interface is abstract, we mark it as non-abstract to
476 | # allow adaptation pattern: IInterface(context)
477 | if md.get("interface_analyzed", False):
478 | return
479 |
480 | for idx, item in enumerate(cls.defs.body):
481 | if isinstance(item, FuncDef):
482 | replacement = self._adjust_interface_function(api, cls.info, item)
483 | elif isinstance(item, OverloadedFuncDef):
484 | replacement = self._adjust_interface_overload(api, cls.info, item)
485 | else:
486 | continue
487 |
488 | cls.defs.body[idx] = replacement
489 |
490 | md["interface_analyzed"] = True
491 |
492 | def _get_metadata(self, typeinfo: TypeInfo) -> Dict[str, Any]:
493 | if "zope" not in typeinfo.metadata:
494 | typeinfo.metadata["zope"] = {}
495 | return typeinfo.metadata["zope"]
496 |
497 | def _is_interface(self, typeinfo: TypeInfo) -> bool:
498 | md = self._get_metadata(typeinfo)
499 | return cast(bool, md.get("is_interface", False))
500 |
501 | def _adjust_interface_function(
502 | self,
503 | api: SemanticAnalyzerPluginInterface,
504 | class_info: TypeInfo,
505 | func_def: FuncDef,
506 | ) -> Statement:
507 |
508 | if func_def.arg_names and func_def.arg_names[0] == "self":
509 | # reveal the common mistake of leaving "self" arguments in the
510 | # interface
511 | api.fail("Interface methods should not have 'self' argument", func_def)
512 | else:
513 | selftype = Instance(
514 | class_info, [], line=class_info.line, column=class_info.column
515 | )
516 | selfarg = Argument(Var("self", None), selftype, None, ARG_POS)
517 |
518 | if isinstance(func_def.type, CallableType):
519 | func_def.type.arg_names.insert(0, "self")
520 | func_def.type.arg_kinds.insert(0, ARG_POS)
521 | func_def.type.arg_types.insert(0, selftype)
522 | func_def.arg_names.insert(0, "self")
523 | func_def.arg_kinds.insert(0, ARG_POS)
524 | func_def.arguments.insert(0, selfarg)
525 |
526 | # 1: We want mypy to consider this method abstract, so that it allows the
527 | # method to have an empty body without causing a warning.
528 | # 2: We want mypy to consider the interface class NOT abstract, so we can use the
529 | # "adaption" pattern.
530 | # Unfortunately whenever mypy sees (1) it will mark the class as abstract,
531 | # forcing (2) to be false. This seems to be a change in mypy 0.990, namely
532 | # https://github.com/python/mypy/pull/13729
533 | #
534 | # Mypy 1.0.0:
535 | # - allows empty bodies for abstract methods in mypy/checker.py:1240
536 | # by testing if
537 | # abstract_status != NOT_ABSTRACT.
538 | # - marks classes as abstract based on their methods in
539 | # mypy/semanal_classprop.py:79 by testing if
540 | # abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT)
541 | #
542 | # Thus we can make (1) and (2) true by setting abstract_status to some value
543 | # distinct from these three NOT_ABSTRACT, IS_ABSTRACT and IMPLICITLY_ABSTRACT.
544 | # These are presently the integers 0, 1, and 2 defined in mypy/nodes.py:738-743.
545 | func_def.abstract_status = HACK_IS_ABSTRACT_NON_PROPAGATING
546 |
547 | return func_def
548 |
549 | def _adjust_interface_overload(
550 | self,
551 | api: SemanticAnalyzerPluginInterface,
552 | class_info: TypeInfo,
553 | overload_def: OverloadedFuncDef,
554 | ) -> Statement:
555 |
556 | for overload_item in overload_def.items:
557 | if isinstance(overload_item, Decorator):
558 | func_def = overload_item.func
559 | else:
560 | assert isinstance(overload_item, FuncDef)
561 | func_def = overload_item
562 |
563 | self._adjust_interface_function(api, class_info, func_def)
564 | return overload_def
565 |
566 | def _report_implementation_problems(
567 | self,
568 | impl_type: Instance,
569 | iface_type: Instance,
570 | api: CheckerPluginInterface,
571 | context: Context,
572 | ) -> None:
573 | # This mimicks mypy's MessageBuilder.report_protocol_problems with
574 | # simplifications for zope interfaces.
575 |
576 | # Blatantly assume we are dealing with this particular implementation
577 | # of CheckerPluginInterface, because it has functionality we want to
578 | # reuse.
579 | assert isinstance(api, TypeChecker)
580 |
581 | impl_info = impl_type.type
582 | iface_info = iface_type.type
583 | iface_members = self._index_members(iface_info)
584 | impl_members = self._index_members(impl_info)
585 |
586 | # Report missing members
587 | missing: Dict[str, List[str]] = defaultdict(list)
588 | for member, member_iface in iface_members.items():
589 | if find_member(member, impl_type, impl_type) is None:
590 | iface_name = member_iface.fullname
591 | if member_iface == iface_info:
592 | # Since interface is directly implemented by this class, we
593 | # can use shorter name.
594 | iface_name = member_iface.name
595 | missing[iface_name].append(member)
596 |
597 | if missing:
598 | for iface_name, members in missing.items():
599 | missing_fmt = ", ".join(sorted(members))
600 | api.fail(
601 | f"'{impl_info.name}' is missing following "
602 | f"'{iface_name}' interface members: {missing_fmt}.",
603 | context,
604 | )
605 |
606 | # Report member type conflicts
607 | for member, member_iface in iface_members.items():
608 | iface_mtype = find_member(member, iface_type, iface_type)
609 | assert iface_mtype is not None
610 | impl_mtype = find_member(member, impl_type, impl_type)
611 | if impl_mtype is None:
612 | continue
613 |
614 | # Find out context for error reporting. If the member is not
615 | # defined inside the class that declares interface implementation,
616 | # show the error near the class definition. Otherwise, show it near
617 | # the member definition.
618 | ctx: Context = impl_info
619 | impl_member_def_info = impl_members.get(member)
620 | impl_name = impl_info.name
621 | if impl_member_def_info is not None:
622 | if impl_member_def_info == impl_info:
623 | ctx = impl_mtype
624 | else:
625 | impl_name = impl_member_def_info.fullname
626 |
627 | iface_name = iface_info.name
628 | if member_iface != iface_info:
629 | iface_name = member_iface.fullname
630 |
631 | if isinstance(impl_mtype, PartialType):
632 | # We don't know how to deal with partial type here. Partial
633 | # types will be resolved later when the implementation class is
634 | # fully type-checked. We are doing our job before that, so all
635 | # we can do is to skip checking of such members.
636 | continue
637 |
638 | if isinstance(iface_mtype, FunctionLike) and isinstance(
639 | impl_mtype, FunctionLike
640 | ):
641 | api.check_override(
642 | override=impl_mtype,
643 | original=iface_mtype,
644 | name=impl_name,
645 | name_in_super=member,
646 | supertype=iface_name,
647 | original_class_or_static=False,
648 | override_class_or_static=False,
649 | node=ctx,
650 | )
651 |
652 | else:
653 | # We could check the field type for compatibility with the code
654 | # below, however this yields too many false-positives in
655 | # real-life projects. The problem is that we can only check
656 | # types defined on a class, instead of instance types, so all
657 | # "descriptor" properties will be falsly reported as type
658 | # mismatches. Instead we opt-out from property type checking
659 | # until we figure out the workaround.
660 |
661 | # api.check_subtype(
662 | # impl_mtype,
663 | # iface_mtype,
664 | # context=ctx,
665 | # subtype_label=f'"{impl_name}" has type',
666 | # supertype_label=f'interface "{iface_name}" defines "{member}" as',
667 | # )
668 | pass
669 |
670 | def _lookup_type(self, fullname: str, api: TypeChecker) -> Instance:
671 | module, names = self._find_module(fullname, api)
672 | container: Union[MypyFile, TypeInfo] = module
673 | for name in names:
674 | sym = container.names[name]
675 | assert isinstance(sym.node, TypeInfo)
676 | container = sym.node
677 | typeinfo = container
678 | assert isinstance(typeinfo, TypeInfo)
679 |
680 | any_type = AnyType(TypeOfAny.from_omitted_generics)
681 | return Instance(typeinfo, [any_type] * len(typeinfo.defn.type_vars))
682 |
683 | def _find_module(
684 | self, fullname: str, api: TypeChecker
685 | ) -> Tuple[MypyFile, Sequence[str]]:
686 | parts = fullname.split(".")
687 | for pn in range(len(parts) - 1, 0, -1):
688 | moduleparts = parts[:pn]
689 | names = parts[pn:]
690 | modulename = ".".join(moduleparts)
691 | if modulename in api.modules:
692 | return api.modules[modulename], names
693 |
694 | raise LookupError(fullname)
695 |
696 | def _index_members(self, typeinfo: TypeInfo) -> Dict[str, TypeInfo]:
697 | # we skip "object" and "Interface" since everyone implements it
698 | members = {}
699 | for base in reversed(typeinfo.mro):
700 | if base.fullname == "builtins.object":
701 | continue
702 | if base.fullname == "zope.interface.interface.Interface":
703 | continue
704 | for name in base.names:
705 | # Members of subtypes override members of supertype
706 | members[name] = base
707 | return members
708 |
709 | def _apply_interface(self, impl: TypeInfo, iface: TypeInfo) -> None:
710 |
711 | md = self._get_metadata(impl)
712 | if "implements" not in md:
713 | md["implements"] = []
714 |
715 | md["implements"].append(iface.fullname)
716 | self.log(f"Found implementation of " f"{iface.fullname}: {impl.fullname}")
717 |
718 | # Make sure implementation is treated as a subtype of an interface. Pretend
719 | # there is a decorator for the class that will create a "type promotion",
720 | # but ensure this only gets applied a single time per interface.
721 | promote = Instance(iface, [])
722 | if promote not in impl._promote:
723 | impl._promote.append(promote)
724 |
725 |
726 | def plugin(version: str) -> PyType[Plugin]:
727 | return ZopeInterfacePlugin
728 |
--------------------------------------------------------------------------------
/src/zope-stubs/__init__.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope (Python 3.6)
2 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/__init__.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from zope.interface.declarations import Declaration as Declaration, alsoProvides as alsoProvides, classImplements as classImplements, classImplementsOnly as classImplementsOnly, classProvides as classProvides, directlyProvidedBy as directlyProvidedBy, directlyProvides as directlyProvides, implementedBy as implementedBy, implementer as implementer, implementer_only as implementer_only, implements as implements, implementsOnly as implementsOnly, moduleProvides as moduleProvides, noLongerProvides as noLongerProvides, providedBy as providedBy, provider as provider, named as named
6 | from zope.interface.interface import Attribute as Attribute, Interface as Interface, interfacemethod as interfacemethod, invariant as invariant, taggedValue as taggedValue
7 | from zope.exceptions import Invalid as Invalid, DoesNotImplement as DoesNotImplement, BrokenImplementation as BrokenImplementation, InvalidInterface as InvalidInterface, BadImplements as BadImplements
8 | from zope.interface import adapter as adapter
9 | from zope.interface import advice as advice
10 | from zope.interface import interfaces as interfaces
11 | from zope.interface import declarations as declarations
12 | from zope.interface import document as document
13 | from zope.interface import exceptions as exceptions
14 | from zope.interface import verify as verify
15 | from zope.interface import ro as ro
16 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/_compat.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface._compat (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | CLASS_TYPES: Any
8 | STRING_TYPES: Any
9 | PYTHON3: bool
10 | PYTHON2: bool
11 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/_flatten.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface._flatten (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/_zope_interface_coptimizations.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface._zope_interface_coptimizations (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | import _interface_coptimizations
8 | import _zope_interface_coptimizations
9 | adapter_hooks: Any
10 |
11 | def getObjectSpecification(*args, **kwargs) -> Any: ...
12 | def implementedBy(*args, **kwargs) -> Any: ...
13 | def providedBy(*args, **kwargs) -> Any: ...
14 |
15 | class ClassProvidesBase(_interface_coptimizations.SpecificationBase):
16 | @classmethod
17 | def __init__(cls, *args, **kwargs) -> None: ...
18 | def __get__(self, *args, **kwargs) -> Any: ...
19 |
20 | class InterfaceBase:
21 | @classmethod
22 | def __init__(cls, *args, **kwargs) -> None: ...
23 | def __adapt__(self, *args, **kwargs) -> Any: ...
24 | def __call__(self, *args, **kwargs) -> Any: ...
25 |
26 | class LookupBase:
27 | @classmethod
28 | def __init__(cls, *args, **kwargs) -> None: ...
29 | def adapter_hook(self, *args, **kwargs) -> Any: ...
30 | def changed(self, *args, **kwargs) -> Any: ...
31 | def lookup(self, *args, **kwargs) -> Any: ...
32 | def lookup1(self, *args, **kwargs) -> Any: ...
33 | def lookupAll(self, *args, **kwargs) -> Any: ...
34 | def queryAdapter(self, *args, **kwargs) -> Any: ...
35 | def subscriptions(self, *args, **kwargs) -> Any: ...
36 |
37 | class ObjectSpecificationDescriptor:
38 | @classmethod
39 | def __init__(cls, *args, **kwargs) -> None: ...
40 | def __get__(self, *args, **kwargs) -> Any: ...
41 |
42 | class SpecificationBase:
43 | @classmethod
44 | def __init__(cls, *args, **kwargs) -> None: ...
45 | def implementedBy(self, *args, **kwargs) -> Any: ...
46 | def isOrExtends(self, *args, **kwargs) -> Any: ...
47 | def providedBy(self, *args, **kwargs) -> Any: ...
48 | def __call__(self, *args, **kwargs) -> Any: ...
49 |
50 | class VerifyingBase(_zope_interface_coptimizations.LookupBase):
51 | @classmethod
52 | def __init__(cls, *args, **kwargs) -> None: ...
53 | def adapter_hook(self, *args, **kwargs) -> Any: ...
54 | def changed(self, *args, **kwargs) -> Any: ...
55 | def lookup(self, *args, **kwargs) -> Any: ...
56 | def lookup1(self, *args, **kwargs) -> Any: ...
57 | def lookupAll(self, *args, **kwargs) -> Any: ...
58 | def queryAdapter(self, *args, **kwargs) -> Any: ...
59 | def subscriptions(self, *args, **kwargs) -> Any: ...
60 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/adapter.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.adapter (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface._zope_interface_coptimizations import LookupBase, VerifyingBase
7 |
8 | class BaseAdapterRegistry:
9 | __bases__: Any = ...
10 | def __init__(self, bases: Any = ...) -> None: ...
11 | def changed(self, originally_changed: Any) -> None: ...
12 | def register(self, required: Any, provided: Any, name: Any, value: Any): ...
13 | def registered(self, required: Any, provided: Any, name: Any = ...): ...
14 | def unregister(self, required: Any, provided: Any, name: Any, value: Optional[Any] = ...): ...
15 | def subscribe(self, required: Any, provided: Any, value: Any) -> None: ...
16 | def unsubscribe(self, required: Any, provided: Any, value: Optional[Any] = ...): ...
17 | def get(self, _: Any): ...
18 |
19 | class LookupBaseFallback:
20 | def __init__(self) -> None: ...
21 | def changed(self, ignored: Optional[Any] = ...) -> None: ...
22 | def lookup(self, required: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...): ...
23 | def lookup1(self, required: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...): ...
24 | def queryAdapter(self, object: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...): ...
25 | def adapter_hook(self, provided: Any, object: Any, name: Any = ..., default: Optional[Any] = ...): ...
26 | def lookupAll(self, required: Any, provided: Any): ...
27 | def subscriptions(self, required: Any, provided: Any): ...
28 | LookupBasePy = LookupBaseFallback
29 | LookupBase = LookupBaseFallback
30 |
31 | class VerifyingBaseFallback(LookupBaseFallback):
32 | def changed(self, originally_changed: Any) -> None: ...
33 | def lookupAll(self, required: Any, provided: Any): ...
34 | def subscriptions(self, required: Any, provided: Any): ...
35 | VerifyingBasePy = VerifyingBaseFallback
36 | VerifyingBase = VerifyingBaseFallback
37 |
38 | class AdapterLookupBase:
39 | def __init__(self, registry: Any) -> None: ...
40 | def changed(self, ignored: Optional[Any] = ...) -> None: ...
41 | def init_extendors(self) -> None: ...
42 | def add_extendor(self, provided: Any) -> None: ...
43 | def remove_extendor(self, provided: Any) -> None: ...
44 | def queryMultiAdapter(self, objects: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...): ...
45 | def names(self, required: Any, provided: Any): ...
46 | def subscribers(self, objects: Any, provided: Any): ...
47 |
48 | class AdapterLookup(AdapterLookupBase, LookupBase): ...
49 |
50 | class AdapterRegistry(BaseAdapterRegistry):
51 | LookupClass: Any = ...
52 | def __init__(self, bases: Any = ...) -> None: ...
53 | def changed(self, originally_changed: Any) -> None: ...
54 |
55 | class VerifyingAdapterLookup(AdapterLookupBase, VerifyingBase): ...
56 |
57 | class VerifyingAdapterRegistry(BaseAdapterRegistry):
58 | LookupClass: Any = ...
59 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/advice.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.advice (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 |
7 | def getFrameInfo(frame: Any): ...
8 | def addClassAdvisor(callback: Any, depth: int = ...): ...
9 | def isClassAdvisor(ob: Any): ...
10 | def determineMetaclass(bases: Any, explicit_mc: Optional[Any] = ...): ...
11 | def minimalBases(classes: Any): ...
12 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/common/__init__.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.common (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/common/idatetime.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.common.idatetime (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface import Interface
7 |
8 | class ITimeDeltaClass(Interface):
9 | min: Any = ...
10 | max: Any = ...
11 | resolution: Any = ...
12 |
13 | class ITimeDelta(ITimeDeltaClass):
14 | days: Any = ...
15 | seconds: Any = ...
16 | microseconds: Any = ...
17 |
18 | class IDateClass(Interface):
19 | min: Any = ...
20 | max: Any = ...
21 | resolution: Any = ...
22 | def today() -> None: ...
23 | def fromtimestamp(timestamp: Any) -> None: ...
24 | def fromordinal(ordinal: Any) -> None: ...
25 |
26 | class IDate(IDateClass):
27 | year: Any = ...
28 | month: Any = ...
29 | day: Any = ...
30 | def replace(year: Any, month: Any, day: Any) -> None: ...
31 | def timetuple() -> None: ...
32 | def toordinal() -> None: ...
33 | def weekday() -> None: ...
34 | def isoweekday() -> None: ...
35 | def isocalendar() -> None: ...
36 | def isoformat() -> None: ...
37 | def ctime() -> None: ...
38 | def strftime(format: Any) -> None: ...
39 |
40 | class IDateTimeClass(Interface):
41 | min: Any = ...
42 | max: Any = ...
43 | resolution: Any = ...
44 | def today() -> None: ...
45 | def now(tz: Optional[Any] = ...) -> None: ...
46 | def utcnow() -> None: ...
47 | def fromtimestamp(timestamp: Any, tz: Optional[Any] = ...) -> None: ...
48 | def utcfromtimestamp(timestamp: Any) -> None: ...
49 | def fromordinal(ordinal: Any) -> None: ...
50 | def combine(date: Any, time: Any) -> None: ...
51 |
52 | class IDateTime(IDate, IDateTimeClass):
53 | year: Any = ...
54 | month: Any = ...
55 | day: Any = ...
56 | hour: Any = ...
57 | minute: Any = ...
58 | second: Any = ...
59 | microsecond: Any = ...
60 | tzinfo: Any = ...
61 | def date() -> None: ...
62 | def time() -> None: ...
63 | def timetz() -> None: ...
64 | def replace(year: Any, month: Any, day: Any, hour: Any, minute: Any, second: Any, microsecond: Any, tzinfo: Any) -> None: ...
65 | def astimezone(tz: Any) -> None: ...
66 | def utcoffset() -> None: ...
67 | def dst() -> None: ...
68 | def tzname() -> None: ...
69 | def timetuple() -> None: ...
70 | def utctimetuple() -> None: ...
71 | def toordinal() -> None: ...
72 | def weekday() -> None: ...
73 | def isoweekday() -> None: ...
74 | def isocalendar() -> None: ...
75 | def isoformat(sep: str = ...) -> None: ...
76 | def ctime() -> None: ...
77 | def strftime(format: Any) -> None: ...
78 |
79 | class ITimeClass(Interface):
80 | min: Any = ...
81 | max: Any = ...
82 | resolution: Any = ...
83 |
84 | class ITime(ITimeClass):
85 | hour: Any = ...
86 | minute: Any = ...
87 | second: Any = ...
88 | microsecond: Any = ...
89 | tzinfo: Any = ...
90 | def replace(hour: Any, minute: Any, second: Any, microsecond: Any, tzinfo: Any) -> None: ...
91 | def isoformat() -> None: ...
92 | def strftime(format: Any) -> None: ...
93 | def utcoffset() -> None: ...
94 | def dst() -> None: ...
95 | def tzname() -> None: ...
96 |
97 | class ITZInfo(Interface):
98 | def utcoffset(dt: Any) -> None: ...
99 | def dst(dt: Any) -> None: ...
100 | def tzname(dt: Any) -> None: ...
101 | def fromutc(dt: Any) -> None: ...
102 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/common/interfaces.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.common.interfaces (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from zope.interface import Interface
6 |
7 | class IException(Interface): ...
8 | class IStandardError(IException): ...
9 | class IWarning(IException): ...
10 | class ISyntaxError(IStandardError): ...
11 | class ILookupError(IStandardError): ...
12 | class IValueError(IStandardError): ...
13 | class IRuntimeError(IStandardError): ...
14 | class IArithmeticError(IStandardError): ...
15 | class IAssertionError(IStandardError): ...
16 | class IAttributeError(IStandardError): ...
17 | class IDeprecationWarning(IWarning): ...
18 | class IEOFError(IStandardError): ...
19 | class IEnvironmentError(IStandardError): ...
20 | class IFloatingPointError(IArithmeticError): ...
21 | class IIOError(IEnvironmentError): ...
22 | class IImportError(IStandardError): ...
23 | class IIndentationError(ISyntaxError): ...
24 | class IIndexError(ILookupError): ...
25 | class IKeyError(ILookupError): ...
26 | class IKeyboardInterrupt(IStandardError): ...
27 | class IMemoryError(IStandardError): ...
28 | class INameError(IStandardError): ...
29 | class INotImplementedError(IRuntimeError): ...
30 | class IOSError(IEnvironmentError): ...
31 | class IOverflowError(IArithmeticError): ...
32 | class IOverflowWarning(IWarning): ...
33 | class IReferenceError(IStandardError): ...
34 | class IRuntimeWarning(IWarning): ...
35 | class IStopIteration(IException): ...
36 | class ISyntaxWarning(IWarning): ...
37 | class ISystemError(IStandardError): ...
38 | class ISystemExit(IException): ...
39 | class ITabError(IIndentationError): ...
40 | class ITypeError(IStandardError): ...
41 | class IUnboundLocalError(INameError): ...
42 | class IUnicodeError(IValueError): ...
43 | class IUserWarning(IWarning): ...
44 | class IZeroDivisionError(IArithmeticError): ...
45 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/common/mapping.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.common.mapping (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional, Union, TypeVar, Generic, Iterable, Iterator, overload
6 | from zope.interface import Interface
7 |
8 | T = TypeVar('T')
9 | KT = TypeVar('KT')
10 | VT = TypeVar('VT')
11 |
12 | class IItemMapping(Interface, Generic[KT, VT]):
13 | def __getitem__(key: KT) -> VT: ...
14 |
15 | class IReadMapping(IItemMapping[KT, VT]):
16 | @overload
17 | def get(self, k: KT) -> Optional[VT]: ...
18 | @overload
19 | def get(self, k: KT, default: Union[VT, T]) -> Union[VT, T]: ...
20 | # def get(key: KT, default: Optional[VT] = ...) -> VT: ...
21 | def __contains__(key: KT) -> bool: ...
22 |
23 | class IWriteMapping(Interface, Generic[KT, VT]):
24 | def __delitem__(key: KT) -> None: ...
25 | def __setitem__(key: KT, value: VT) -> None: ...
26 |
27 | class IEnumerableMapping(IReadMapping[KT, VT]):
28 | def keys() -> Iterable[KT]: ...
29 | def __iter__() -> Iterator[VT]: ...
30 | def values() -> Iterable[VT]: ...
31 | def items() -> Iterable[tuple[KT, VT]]: ...
32 | def __len__() -> int: ...
33 |
34 | class IMapping(IWriteMapping[KT, VT], IEnumerableMapping[KT, VT]): ...
35 |
36 | class IIterableMapping(IEnumerableMapping[KT, VT]):
37 | def iterkeys() -> Iterable[KT]: ...
38 | def itervalues() -> Iterable[VT]: ...
39 | def iteritems() -> Iterable[tuple[KT, VT]]: ...
40 |
41 | class IClonableMapping(Interface):
42 | def copy() -> IClonableMapping: ...
43 |
44 | class IExtendedReadMapping(IIterableMapping[KT, VT]):
45 | def has_key(key: KT) -> bool: ...
46 |
47 | class IExtendedWriteMapping(IWriteMapping[KT, VT]):
48 | def clear() -> None: ...
49 | def update(d: Any) -> None: ...
50 | def setdefault(key: KT, default: Optional[VT] = ...) -> None: ...
51 | def pop(k: KT, *args: Any) -> None: ...
52 | def popitem() -> VT: ...
53 |
54 | class IFullMapping(IExtendedReadMapping[KT, VT], IExtendedWriteMapping[KT, VT], IClonableMapping[KT, VT], IMapping[KT, VT]): ...
55 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/common/sequence.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.common.sequence (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface import Interface
7 |
8 | __docformat__: str
9 |
10 | class IMinimalSequence(Interface):
11 | def __getitem__(index: Any) -> None: ...
12 |
13 | class IFiniteSequence(IMinimalSequence):
14 | def __len__() -> None: ...
15 |
16 | class IReadSequence(IFiniteSequence):
17 | def __contains__(item: Any) -> None: ...
18 | def __lt__(other: Any) -> None: ...
19 | def __le__(other: Any) -> None: ...
20 | def __eq__(other: Any) -> None: ...
21 | def __ne__(other: Any) -> None: ...
22 | def __gt__(other: Any) -> None: ...
23 | def __ge__(other: Any) -> None: ...
24 | def __add__(other: Any) -> None: ...
25 | def __mul__(n: Any) -> None: ...
26 | def __rmul__(n: Any) -> None: ...
27 | def __getslice__(i: Any, j: Any) -> None: ...
28 |
29 | class IExtendedReadSequence(IReadSequence):
30 | def count(item: Any) -> None: ...
31 | def index(item: Any, *args: Any) -> None: ...
32 |
33 | class IUniqueMemberWriteSequence(Interface):
34 | def __setitem__(index: Any, item: Any) -> None: ...
35 | def __delitem__(index: Any) -> None: ...
36 | def __setslice__(i: Any, j: Any, other: Any) -> None: ...
37 | def __delslice__(i: Any, j: Any) -> None: ...
38 | def __iadd__(y: Any) -> None: ...
39 | def append(item: Any) -> None: ...
40 | def insert(index: Any, item: Any) -> None: ...
41 | def pop(index: int = ...) -> None: ...
42 | def remove(item: Any) -> None: ...
43 | def reverse() -> None: ...
44 | def sort(cmpfunc: Optional[Any] = ...) -> None: ...
45 | def extend(iterable: Any) -> None: ...
46 |
47 | class IWriteSequence(IUniqueMemberWriteSequence):
48 | def __imul__(n: Any) -> None: ...
49 |
50 | class ISequence(IReadSequence, IWriteSequence): ...
51 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/declarations.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.declarations (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 | from zope.interface._zope_interface_coptimizations import ClassProvidesBase
7 | from zope.interface.interface import Specification
8 |
9 | __docformat__: str
10 | BuiltinImplementationSpecifications: Any
11 |
12 | class named:
13 | name: Any = ...
14 | def __init__(self, name: Any) -> None: ...
15 | def __call__(self, ob: Any): ...
16 |
17 | class Declaration(Specification):
18 | def __init__(self, *interfaces: Any) -> None: ...
19 | def changed(self, originally_changed: Any) -> None: ...
20 | def __contains__(self, interface: Any): ...
21 | def __iter__(self): ...
22 | def flattened(self): ...
23 | def __sub__(self, other: Any): ...
24 | def __add__(self, other: Any): ...
25 | __radd__: Any = ...
26 |
27 | class Implements(Declaration):
28 | inherit: Any = ...
29 | declared: Any = ...
30 | __name__: str = ...
31 | @classmethod
32 | def named(cls, name: Any, *interfaces: Any): ...
33 | def __reduce__(self): ...
34 | def __hash__(self): ...
35 | def __lt__(self, other: Any): ...
36 | def __le__(self, other: Any): ...
37 | def __gt__(self, other: Any): ...
38 | def __ge__(self, other: Any): ...
39 |
40 | def implementedByFallback(cls): ...
41 | implementedBy = implementedByFallback
42 |
43 | def classImplementsOnly(cls, *interfaces: Any) -> None: ...
44 | def classImplements(cls, *interfaces: Any) -> None: ...
45 |
46 | class implementer:
47 | interfaces: Any = ...
48 | def __init__(self, *interfaces: Any) -> None: ...
49 | def __call__(self, ob: Any): ...
50 |
51 | class implementer_only:
52 | interfaces: Any = ...
53 | def __init__(self, *interfaces: Any) -> None: ...
54 | def __call__(self, ob: Any): ...
55 |
56 | def implements(*interfaces: Any) -> None: ...
57 | def implementsOnly(*interfaces: Any) -> None: ...
58 |
59 | class Provides(Declaration):
60 | def __init__(self, cls: Any, *interfaces: Any) -> None: ...
61 | def __reduce__(self): ...
62 | __module__: str = ...
63 | def __get__(self, inst: Any, cls: Any): ...
64 | ProvidesClass = Provides
65 | InstanceDeclarations: Any
66 |
67 | def directlyProvides(object: Any, *interfaces: Any) -> None: ...
68 | def alsoProvides(object: Any, *interfaces: Any) -> None: ...
69 | def noLongerProvides(object: Any, interface: Any) -> None: ...
70 |
71 | class ClassProvidesBaseFallback:
72 | def __get__(self, inst: Any, cls: Any): ...
73 | ClassProvidesBasePy = ClassProvidesBaseFallback
74 | ClassProvidesBase = ClassProvidesBaseFallback
75 |
76 | class ClassProvides(Declaration, ClassProvidesBase):
77 | def __init__(self, cls: Any, metacls: Any, *interfaces: Any) -> None: ...
78 | def __reduce__(self): ...
79 | __get__: Any = ...
80 |
81 | def directlyProvidedBy(object: Any): ...
82 | def classProvides(*interfaces: Any) -> None: ...
83 |
84 | class provider:
85 | interfaces: Any = ...
86 | def __init__(self, *interfaces: Any) -> None: ...
87 | def __call__(self, ob: Any): ...
88 |
89 | def moduleProvides(*interfaces: Any) -> None: ...
90 | def ObjectSpecification(direct: Any, cls: Any): ...
91 | def getObjectSpecificationFallback(ob: Any): ...
92 | getObjectSpecification = getObjectSpecificationFallback
93 |
94 | def providedByFallback(ob: Any): ...
95 | providedBy = providedByFallback
96 |
97 | class ObjectSpecificationDescriptorFallback:
98 | def __get__(self, inst: Any, cls: Any): ...
99 | ObjectSpecificationDescriptor = ObjectSpecificationDescriptorFallback
100 | objectSpecificationDescriptor: Any
101 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/document.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.document (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | def asStructuredText(I: Any, munge: int = ..., rst: bool = ...): ...
8 | def asReStructuredText(I: Any, munge: int = ...): ...
9 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/exceptions.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.exceptions (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | class Invalid(Exception): ...
8 |
9 | class DoesNotImplement(Invalid):
10 | interface: Any = ...
11 | def __init__(self, interface: Any) -> None: ...
12 |
13 | class BrokenImplementation(Invalid):
14 | interface: Any = ...
15 | name: Any = ...
16 | def __init__(self, interface: Any, name: Any) -> None: ...
17 |
18 | class BrokenMethodImplementation(Invalid):
19 | method: Any = ...
20 | mess: Any = ...
21 | def __init__(self, method: Any, mess: Any) -> None: ...
22 |
23 | class InvalidInterface(Exception): ...
24 | class BadImplements(TypeError): ...
25 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/interface.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.interface (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 |
7 | CO_VARARGS: int
8 | CO_VARKEYWORDS: int
9 | TAGGED_DATA: str
10 |
11 | def invariant(call: Any): ...
12 | def taggedValue(key: Any, value: Any): ...
13 |
14 | class Element:
15 | __name__: Any = ...
16 | __doc__: Any = ...
17 | def __init__(self, __name__: Any, __doc__: str = ...) -> None: ...
18 | def getName(self): ...
19 | def getDoc(self): ...
20 | def getTaggedValue(self, tag: Any): ...
21 | def queryTaggedValue(self, tag: Any, default: Optional[Any] = ...): ...
22 | def getTaggedValueTags(self): ...
23 | def setTaggedValue(self, tag: Any, value: Any) -> None: ...
24 |
25 | class SpecificationBasePy:
26 | def providedBy(self, ob: Any) -> bool: ...
27 | def implementedBy(self, cls: Any) -> bool: ...
28 | def isOrExtends(self, interface: Any) -> bool: ...
29 | __call__: Any = ...
30 | SpecificationBase = SpecificationBasePy
31 |
32 | class InterfaceBasePy:
33 | def __call__(self, obj: Any, alternate: Any = ...): ...
34 | def __adapt__(self, obj: Any): ...
35 | InterfaceBase = InterfaceBasePy
36 | adapter_hooks: Any
37 |
38 | class Specification(SpecificationBase):
39 | dependents: Any = ...
40 | __bases__: Any = ...
41 | def __init__(self, bases: Any = ...) -> None: ...
42 | def subscribe(self, dependent: Any) -> None: ...
43 | def unsubscribe(self, dependent: Any) -> None: ...
44 | __sro__: Any = ...
45 | __iro__: Any = ...
46 | def changed(self, originally_changed: Any) -> None: ...
47 | def interfaces(self) -> None: ...
48 | def extends(self, interface: Any, strict: bool = ...): ...
49 | def weakref(self, callback: Optional[Any] = ...): ...
50 | def get(self, name: Any, default: Optional[Any] = ...): ...
51 |
52 | class InterfaceClass(type, Element, InterfaceBase, Specification):
53 | __module__: Any = ...
54 | __identifier__: Any = ...
55 | def __init__(self, name: Any, bases: Any = ..., attrs: Optional[Any] = ..., __doc__: Optional[Any] = ..., __module__: Optional[Any] = ...) -> None: ...
56 | def interfaces(self) -> None: ...
57 | def getBases(self): ...
58 | def isEqualOrExtendedBy(self, other: Any): ...
59 | def names(self, all: bool = ...): ...
60 | def __iter__(self): ...
61 | def namesAndDescriptions(self, all: bool = ...): ...
62 | def getDescriptionFor(self, name: Any): ...
63 | def __getitem__(self, key, default: Optional[Any] = ...) -> Any: ...
64 | def __contains__(self, name: Any): ...
65 | def direct(self, name: Any): ...
66 | def queryDescriptionFor(self, name: Any, default: Optional[Any] = ...): ...
67 | def validateInvariants(self, obj: Any, errors: Optional[Any] = ...) -> None: ...
68 | def __reduce__(self): ...
69 | def __hash__(self): ...
70 | def __eq__(self, other: Any): ...
71 | def __ne__(self, other: Any): ...
72 | def __lt__(self, other: Any): ...
73 | def __le__(self, other: Any): ...
74 | def __gt__(self, other: Any): ...
75 | def __ge__(self, other: Any): ...
76 |
77 | class Interface(metaclass=InterfaceClass): ...
78 |
79 | class Attribute(Element):
80 | interface: Any = ...
81 |
82 | class Method(Attribute):
83 | positional: Any = ...
84 | required: Any = ...
85 | varargs: Any = ...
86 | kwargs: Any = ...
87 | optional: Any = ...
88 | def __call__(self, *args: Any, **kw: Any) -> None: ...
89 | def getSignatureInfo(self): ...
90 | def getSignatureString(self): ...
91 |
92 | def fromFunction(func: Any, interface: Optional[Any] = ..., imlevel: int = ..., name: Optional[Any] = ...): ...
93 | def fromMethod(meth: Any, interface: Optional[Any] = ..., name: Optional[Any] = ...): ...
94 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/interfaces.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.interfaces (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface.interface import Interface
7 |
8 | __docformat__: str
9 |
10 | class IElement(Interface):
11 | __name__: Any = ...
12 | __doc__: Any = ...
13 | def getTaggedValue(tag: Any) -> None: ...
14 | def queryTaggedValue(tag: Any, default: Optional[Any] = ...) -> None: ...
15 | def getTaggedValueTags() -> None: ...
16 | def setTaggedValue(tag: Any, value: Any) -> None: ...
17 |
18 | class IAttribute(IElement):
19 | interface: Any = ...
20 |
21 | class IMethod(IAttribute):
22 | def getSignatureInfo() -> None: ...
23 | def getSignatureString() -> None: ...
24 |
25 | class ISpecification(Interface):
26 | @staticmethod
27 | def providedBy(object: Any) -> bool: ...
28 | @staticmethod
29 | def implementedBy(class_: Any) -> bool: ...
30 | @staticmethod
31 | def isOrExtends(other: Any) -> bool: ...
32 | @staticmethod
33 | def extends(other: Any, strict: bool = ...) -> None: ...
34 | @staticmethod
35 | def weakref(callback: Optional[Any] = ...) -> None: ...
36 | def get(name: Any, default: Optional[Any] = ...) -> None: ...
37 |
38 | class IInterface(ISpecification, IElement):
39 | def names(all: bool = ...) -> None: ...
40 | def namesAndDescriptions(all: bool = ...) -> None: ...
41 | def __getitem__(name: Any) -> None: ...
42 | def direct(name: Any) -> None: ...
43 | def validateInvariants(obj: Any, errors: Optional[Any] = ...) -> None: ...
44 | def __contains__(name: Any) -> None: ...
45 | def __iter__() -> None: ...
46 | __module__: Any = ...
47 |
48 | class IDeclaration(ISpecification):
49 | def __contains__(interface: Any) -> None: ...
50 | def __iter__() -> None: ...
51 | def flattened() -> None: ...
52 | def __sub__(interfaces: Any) -> None: ...
53 | def __add__(interfaces: Any) -> None: ...
54 | def __nonzero__() -> None: ...
55 |
56 | class IInterfaceDeclaration(Interface):
57 | def providedBy(ob: Any) -> None: ...
58 | def implementedBy(class_: Any) -> None: ...
59 | def classImplements(class_: Any, *interfaces: Any) -> None: ...
60 | def implementer(*interfaces: Any) -> None: ...
61 | def classImplementsOnly(class_: Any, *interfaces: Any) -> None: ...
62 | def implementer_only(*interfaces: Any) -> None: ...
63 | def directlyProvidedBy(object: Any) -> None: ...
64 | def directlyProvides(object: Any, *interfaces: Any) -> None: ...
65 | def alsoProvides(object: Any, *interfaces: Any) -> None: ...
66 | def noLongerProvides(object: Any, interface: Any) -> None: ...
67 | def implements(*interfaces: Any) -> None: ...
68 | def implementsOnly(*interfaces: Any) -> None: ...
69 | def classProvides(*interfaces: Any) -> None: ...
70 | def provider(*interfaces: Any) -> None: ...
71 | def moduleProvides(*interfaces: Any) -> None: ...
72 | def Declaration(*interfaces: Any) -> None: ...
73 |
74 | class IAdapterRegistry(Interface):
75 | def register(required: Any, provided: Any, name: Any, value: Any) -> None: ...
76 | def registered(required: Any, provided: Any, name: Any = ...) -> None: ...
77 | def lookup(required: Any, provided: Any, name: str = ..., default: Optional[Any] = ...) -> None: ...
78 | def queryMultiAdapter(objects: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
79 | def lookup1(required: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
80 | def queryAdapter(object: Any, provided: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
81 | def adapter_hook(provided: Any, object: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
82 | def lookupAll(required: Any, provided: Any) -> None: ...
83 | def names(required: Any, provided: Any) -> None: ...
84 | def subscribe(required: Any, provided: Any, subscriber: Any, name: Any = ...) -> None: ...
85 | def subscriptions(required: Any, provided: Any, name: Any = ...) -> None: ...
86 | def subscribers(objects: Any, provided: Any, name: Any = ...) -> None: ...
87 |
88 | class ComponentLookupError(LookupError): ...
89 | class Invalid(Exception): ...
90 |
91 | class IObjectEvent(Interface):
92 | object: Any = ...
93 |
94 | class ObjectEvent:
95 | object: Any = ...
96 | def __init__(self, object: Any) -> None: ...
97 |
98 | class IComponentLookup(Interface):
99 | adapters: Any = ...
100 | utilities: Any = ...
101 | def queryAdapter(object: Any, interface: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
102 | def getAdapter(object: Any, interface: Any, name: Any = ...) -> None: ...
103 | def queryMultiAdapter(objects: Any, interface: Any, name: Any = ..., default: Optional[Any] = ...) -> None: ...
104 | def getMultiAdapter(objects: Any, interface: Any, name: Any = ...) -> None: ...
105 | def getAdapters(objects: Any, provided: Any) -> None: ...
106 | def subscribers(objects: Any, provided: Any) -> None: ...
107 | def handle(*objects: Any) -> None: ...
108 | def queryUtility(interface: Any, name: str = ..., default: Optional[Any] = ...) -> None: ...
109 | def getUtilitiesFor(interface: Any) -> None: ...
110 | def getAllUtilitiesRegisteredFor(interface: Any) -> None: ...
111 |
112 | class IRegistration(Interface):
113 | registry: Any = ...
114 | name: Any = ...
115 | info: Any = ...
116 |
117 | class IUtilityRegistration(IRegistration):
118 | factory: Any = ...
119 | component: Any = ...
120 | provided: Any = ...
121 |
122 | class _IBaseAdapterRegistration(IRegistration):
123 | factory: Any = ...
124 | required: Any = ...
125 | provided: Any = ...
126 |
127 | class IAdapterRegistration(_IBaseAdapterRegistration): ...
128 | class ISubscriptionAdapterRegistration(_IBaseAdapterRegistration): ...
129 |
130 | class IHandlerRegistration(IRegistration):
131 | handler: Any = ...
132 | required: Any = ...
133 |
134 | class IRegistrationEvent(IObjectEvent): ...
135 | class RegistrationEvent(ObjectEvent): ...
136 | class IRegistered(IRegistrationEvent): ...
137 | class Registered(RegistrationEvent): ...
138 | class IUnregistered(IRegistrationEvent): ...
139 | class Unregistered(RegistrationEvent): ...
140 |
141 | class IComponentRegistry(Interface):
142 | def registerUtility(component: Optional[Any] = ..., provided: Optional[Any] = ..., name: Any = ..., info: Any = ..., factory: Optional[Any] = ...) -> None: ...
143 | def unregisterUtility(component: Optional[Any] = ..., provided: Optional[Any] = ..., name: Any = ..., factory: Optional[Any] = ...) -> None: ...
144 | def registeredUtilities() -> None: ...
145 | def registerAdapter(factory: Any, required: Optional[Any] = ..., provided: Optional[Any] = ..., name: Any = ..., info: Any = ...) -> None: ...
146 | def unregisterAdapter(factory: Optional[Any] = ..., required: Optional[Any] = ..., provided: Optional[Any] = ..., name: Any = ...) -> None: ...
147 | def registeredAdapters() -> None: ...
148 | def registerSubscriptionAdapter(factory: Any, required: Optional[Any] = ..., provides: Optional[Any] = ..., name: Any = ..., info: str = ...) -> None: ...
149 | def unregisterSubscriptionAdapter(factory: Optional[Any] = ..., required: Optional[Any] = ..., provides: Optional[Any] = ..., name: Any = ...) -> None: ...
150 | def registeredSubscriptionAdapters() -> None: ...
151 | def registerHandler(handler: Any, required: Optional[Any] = ..., name: Any = ..., info: str = ...) -> None: ...
152 | def unregisterHandler(handler: Optional[Any] = ..., required: Optional[Any] = ..., name: Any = ...) -> None: ...
153 | def registeredHandlers() -> None: ...
154 |
155 | class IComponents(IComponentLookup, IComponentRegistry): ...
156 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/registry.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.registry (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Generic, Iterator, Optional, Type, TypeVar, Tuple
6 |
7 | T = TypeVar("T")
8 |
9 | class _UnhashableComponentCounter:
10 | def __init__(self, otherdict: Any) -> None: ...
11 | def __getitem__(self, key: Any): ...
12 | def __setitem__(self, component: Any, count: Any): ...
13 | def __delitem__(self, component: Any): ...
14 |
15 | class _UtilityRegistrations:
16 | def __init__(self, utilities: Any, utility_registrations: Any) -> None: ...
17 | def registerUtility(self, provided: Any, name: Any, component: Any, info: Any, factory: Any) -> None: ...
18 | def unregisterUtility(self, provided: Any, name: Any, component: Any) -> None: ...
19 |
20 | class Components:
21 | __name__: Any = ...
22 | __bases__: Any = ...
23 | def __init__(self, name: str = ..., bases: Any = ...) -> None: ...
24 | def __reduce__(self): ...
25 | def registerUtility(self, component: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ..., info: str = ..., event: bool = ..., factory: Optional[Any] = ...): ...
26 | def unregisterUtility(self, component: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ..., factory: Optional[Any] = ...): ...
27 | def registeredUtilities(self) -> None: ...
28 | def queryUtility(self, provided: Type[T], name: str = ..., default: Optional[Any] = ...) -> Optional[T]: ...
29 | def getUtility(self, provided: Type[T], name: str = ...) -> T: ...
30 | def getUtilitiesFor(self, interface: Type[T]) -> Iterator[Tuple[str, T]]: ...
31 | def getAllUtilitiesRegisteredFor(self, interface: Any): ...
32 | def registerAdapter(self, factory: Any, required: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ..., info: str = ..., event: bool = ...) -> None: ...
33 | def unregisterAdapter(self, factory: Optional[Any] = ..., required: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ...): ...
34 | def registeredAdapters(self) -> None: ...
35 | def queryAdapter(self, object: Any, interface: Type[T], name: str = ..., default: Optional[Any] = ...) -> Optional[T]: ...
36 | def getAdapter(self, object: Any, interface: Type[T], name: str = ...) -> T: ...
37 | def queryMultiAdapter(self, objects: Any, interface: Type[T], name: str = ..., default: Optional[Any] = ...) -> Optional[T]: ...
38 | def getMultiAdapter(self, objects: Any, interface: Type[T], name: str = ...) -> T: ...
39 | def getAdapters(self, objects: Any, provided: Type[T]) -> Iterator[Tuple[str, T]]: ...
40 | def registerSubscriptionAdapter(self, factory: Any, required: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ..., info: str = ..., event: bool = ...) -> None: ...
41 | def registeredSubscriptionAdapters(self) -> None: ...
42 | def unregisterSubscriptionAdapter(self, factory: Optional[Any] = ..., required: Optional[Any] = ..., provided: Optional[Any] = ..., name: str = ...): ...
43 | def subscribers(self, objects: Any, provided: Type[T]) -> T: ...
44 | def registerHandler(self, factory: Any, required: Optional[Any] = ..., name: str = ..., info: str = ..., event: bool = ...) -> None: ...
45 | def registeredHandlers(self) -> None: ...
46 | def unregisterHandler(self, factory: Optional[Any] = ..., required: Optional[Any] = ..., name: str = ...): ...
47 | def handle(self, *objects: Any) -> None: ...
48 |
49 | class UtilityRegistration:
50 | def __init__(self, registry: Any, provided: Any, name: Any, component: Any, doc: Any, factory: Optional[Any] = ...) -> None: ...
51 | def __hash__(self): ...
52 | def __eq__(self, other: Any): ...
53 | def __ne__(self, other: Any): ...
54 | def __lt__(self, other: Any): ...
55 | def __le__(self, other: Any): ...
56 | def __gt__(self, other: Any): ...
57 | def __ge__(self, other: Any): ...
58 |
59 | class AdapterRegistration:
60 | def __init__(self, registry: Any, required: Any, provided: Any, name: Any, component: Any, doc: Any) -> None: ...
61 | def __hash__(self): ...
62 | def __eq__(self, other: Any): ...
63 | def __ne__(self, other: Any): ...
64 | def __lt__(self, other: Any): ...
65 | def __le__(self, other: Any): ...
66 | def __gt__(self, other: Any): ...
67 | def __ge__(self, other: Any): ...
68 |
69 | class SubscriptionRegistration(AdapterRegistration): ...
70 |
71 | class HandlerRegistration(AdapterRegistration):
72 | def __init__(self, registry: Any, required: Any, name: Any, handler: Any, doc: Any) -> None: ...
73 | @property
74 | def factory(self): ...
75 | provided: Any = ...
76 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/ro.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.ro (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | __docformat__: str
8 |
9 | def ro(object: Any): ...
10 |
--------------------------------------------------------------------------------
/src/zope-stubs/interface/verify.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.interface.verify (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | MethodTypes: Any
8 |
9 | def verifyClass(iface: Any, candidate: Any, tentative: int = ...): ...
10 | def verifyObject(iface: Any, candidate: Any, tentative: int = ...): ...
11 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/__init__.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from zope.schema._bootstrapinterfaces import NO_VALUE as NO_VALUE
6 | from zope.schema._field import ASCII as ASCII, ASCIILine as ASCIILine, Bool as Bool, Bytes as Bytes, BytesLine as BytesLine, Choice as Choice, Collection as Collection, Complex as Complex, Container as Container, Date as Date, Datetime as Datetime, Decimal as Decimal, Dict as Dict, DottedName as DottedName, Field as Field, Float as Float, FrozenSet as FrozenSet, Id as Id, Int as Int, Integral as Integral, InterfaceField as InterfaceField, Iterable as Iterable, List as List, Mapping as Mapping, MinMaxLen as MinMaxLen, MutableMapping as MutableMapping, MutableSequence as MutableSequence, NativeString as NativeString, NativeStringLine as NativeStringLine, Number as Number, Object as Object, Orderable as Orderable, Password as Password, PythonIdentifier as PythonIdentifier, Rational as Rational, Real as Real, Sequence as Sequence, Set as Set, SourceText as SourceText, Text as Text, TextLine as TextLine, Time as Time, Timedelta as Timedelta, Tuple as Tuple, URI as URI
7 | from zope.schema._schema import getFieldNames as getFieldNames, getFieldNamesInOrder as getFieldNamesInOrder, getFields as getFields, getFieldsInOrder as getFieldsInOrder, getSchemaValidationErrors as getSchemaValidationErrors, getValidationErrors as getValidationErrors
8 | from zope.schema.accessors import accessors as accessors
9 | from zope.schema.interfaces import ValidationError as ValidationError
10 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_bootstrapfields.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._bootstrapfields (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | import threading
6 | from typing import Any, Optional
7 | from zope.interface import Attribute
8 | from zope.schema._bootstrapinterfaces import ValidationError
9 |
10 | __docformat__: str
11 |
12 | class _NotGiven: ...
13 |
14 | class ValidatedProperty:
15 | def __init__(self, name: Any, check: Optional[Any] = ..., allow_none: bool = ...) -> None: ...
16 | def __set__(self, inst: Any, value: Any) -> None: ...
17 | def __get__(self, inst: Any, owner: Any): ...
18 |
19 | class DefaultProperty(ValidatedProperty):
20 | def __get__(self, inst: Any, owner: Any): ...
21 |
22 | def getFields(schema: Any): ...
23 |
24 | class _DocStringHelpers:
25 | @staticmethod
26 | def docstring_to_lines(docstring: Any): ...
27 | @staticmethod
28 | def make_class_directive(kind: Any): ...
29 | @classmethod
30 | def make_field(cls, name: Any, value: Any): ...
31 | @classmethod
32 | def make_class_field(cls, name: Any, kind: Any): ...
33 |
34 | class Field(Attribute):
35 | context: Any = ...
36 | missing_value: Any = ...
37 | order: int = ...
38 | default: Any = ...
39 | __name__: Any = ...
40 | interface: Any = ...
41 | title: Any = ...
42 | description: Any = ...
43 | required: Any = ...
44 | readonly: Any = ...
45 | constraint: Any = ...
46 | defaultFactory: Any = ...
47 | def __init__(self, title: str = ..., description: str = ..., __name__: str = ..., required: bool = ..., readonly: bool = ..., constraint: Optional[Any] = ..., default: Optional[Any] = ..., defaultFactory: Optional[Any] = ..., missing_value: Any = ...) -> None: ...
48 | def constraint(self, value: Any): ...
49 | def bind(self, context: Any): ...
50 | def validate(self, value: Any) -> None: ...
51 | def __hash__(self): ...
52 | def __eq__(self, other: Any): ...
53 | def __ne__(self, other: Any): ...
54 | def get(self, object: Any): ...
55 | def query(self, object: Any, default: Optional[Any] = ...): ...
56 | def set(self, object: Any, value: Any) -> None: ...
57 | def getExtraDocLines(self): ...
58 | def getDoc(self): ...
59 |
60 | class Container(Field): ...
61 | class Iterable(Container): ...
62 |
63 | class Orderable:
64 | min: Any = ...
65 | max: Any = ...
66 | default: Any = ...
67 | def __init__(self, min: Optional[Any] = ..., max: Optional[Any] = ..., default: Optional[Any] = ..., **kw: Any) -> None: ...
68 |
69 | class MinMaxLen:
70 | min_length: int = ...
71 | max_length: Any = ...
72 | def __init__(self, min_length: int = ..., max_length: Optional[Any] = ..., **kw: Any) -> None: ...
73 |
74 | class Text(MinMaxLen, Field):
75 | def __init__(self, *args: Any, **kw: Any) -> None: ...
76 | def fromUnicode(self, str: Any): ...
77 |
78 | class TextLine(Text):
79 | def constraint(self, value: Any): ...
80 |
81 | class Password(TextLine):
82 | UNCHANGED_PASSWORD: Any = ...
83 | def set(self, context: Any, value: Any): ...
84 | def validate(self, value: Any): ...
85 |
86 | class Bool(Field):
87 | def set(self, object: Any, value: Any) -> None: ...
88 | def fromUnicode(self, value: Any): ...
89 | def fromBytes(self, value: Any): ...
90 |
91 | class InvalidNumberLiteral(ValueError, ValidationError): ...
92 |
93 | class Number(Orderable, Field):
94 | def fromUnicode(self, value: Any): ...
95 | fromBytes: Any = ...
96 | def fromBytes(self, value: Any): ...
97 |
98 | class Complex(Number): ...
99 | class Real(Complex): ...
100 | class Rational(Real): ...
101 | class InvalidIntLiteral(ValueError, ValidationError): ...
102 | class Integral(Rational): ...
103 | class Int(Integral): ...
104 |
105 | class _ObjectsBeingValidated(threading.local):
106 | ids_being_validated: Any = ...
107 | def __init__(self) -> None: ...
108 |
109 | def get_schema_validation_errors(schema: Any, value: Any, _validating_objects: Any = ...): ...
110 | def get_validation_errors(schema: Any, value: Any, validate_invariants: bool = ...): ...
111 |
112 | class Object(Field):
113 | schema: Any = ...
114 | validate_invariants: Any = ...
115 | def __init__(self, schema: Any = ..., **kw: Any) -> None: ...
116 | def getExtraDocLines(self): ...
117 | def set(self, object: Any, value: Any) -> None: ...
118 |
119 | class BeforeObjectAssignedEvent:
120 | object: Any = ...
121 | name: Any = ...
122 | context: Any = ...
123 | def __init__(self, object: Any, name: Any, context: Any) -> None: ...
124 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_bootstrapinterfaces.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._bootstrapinterfaces (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | import zope.interface
6 | from typing import Any, Optional
7 |
8 | class StopValidation(Exception): ...
9 |
10 | class ValidationError(zope.interface.Invalid):
11 | field: Any = ...
12 | value: Any = ...
13 | def with_field_and_value(self, field: Any, value: Any): ...
14 | def doc(self): ...
15 | def __lt__(self, other: Any): ...
16 | def __eq__(self, other: Any): ...
17 | __hash__: Any = ...
18 |
19 | class RequiredMissing(ValidationError):
20 | __doc__: Any = ...
21 |
22 | class WrongType(ValidationError):
23 | __doc__: Any = ...
24 | expected_type: Any = ...
25 | value: Any = ...
26 | def __init__(self, value: Optional[Any] = ..., expected_type: Optional[Any] = ..., name: Optional[Any] = ..., *args: Any) -> None: ...
27 |
28 | class OutOfBounds(ValidationError):
29 | bound: Any = ...
30 | TOO_LARGE: Any = ...
31 | TOO_SMALL: Any = ...
32 | violation_direction: Any = ...
33 | value: Any = ...
34 | def __init__(self, value: Optional[Any] = ..., bound: Optional[Any] = ..., *args: Any) -> None: ...
35 |
36 | class OrderableOutOfBounds(OutOfBounds): ...
37 |
38 | class TooBig(OrderableOutOfBounds):
39 | __doc__: Any = ...
40 | violation_direction: Any = ...
41 |
42 | class TooSmall(OrderableOutOfBounds):
43 | __doc__: Any = ...
44 | violation_direction: Any = ...
45 |
46 | class LenOutOfBounds(OutOfBounds): ...
47 |
48 | class TooLong(LenOutOfBounds):
49 | __doc__: Any = ...
50 | violation_direction: Any = ...
51 |
52 | class TooShort(LenOutOfBounds):
53 | __doc__: Any = ...
54 | violation_direction: Any = ...
55 |
56 | class InvalidValue(ValidationError):
57 | __doc__: Any = ...
58 |
59 | class ConstraintNotSatisfied(ValidationError):
60 | __doc__: Any = ...
61 |
62 | class NotAContainer(ValidationError):
63 | __doc__: Any = ...
64 |
65 | class NotAnIterator(ValidationError):
66 | __doc__: Any = ...
67 |
68 | class WrongContainedType(ValidationError):
69 | __doc__: Any = ...
70 | errors: Any = ...
71 | def __init__(self, errors: Optional[Any] = ..., name: Optional[Any] = ..., *args: Any) -> None: ...
72 |
73 | class SchemaNotCorrectlyImplemented(WrongContainedType):
74 | __doc__: Any = ...
75 | schema_errors: Any = ...
76 | invariant_errors: Any = ...
77 | def __init__(self, errors: Optional[Any] = ..., name: Optional[Any] = ..., schema_errors: Optional[Any] = ..., invariant_errors: Any = ..., *args: Any) -> None: ...
78 |
79 | class SchemaNotFullyImplemented(ValidationError):
80 | __doc__: Any = ...
81 |
82 | class SchemaNotProvided(ValidationError):
83 | __doc__: Any = ...
84 | schema: Any = ...
85 | value: Any = ...
86 | def __init__(self, schema: Optional[Any] = ..., value: Optional[Any] = ..., *args: Any) -> None: ...
87 |
88 | class NotAnInterface(WrongType, SchemaNotProvided):
89 | expected_type: Any = ...
90 | def __init__(self, value: Any, name: Any) -> None: ...
91 |
92 | class IFromUnicode(zope.interface.Interface):
93 | def fromUnicode(value: Any) -> None: ...
94 |
95 | class IFromBytes(zope.interface.Interface):
96 | def fromBytes(value: Any) -> None: ...
97 |
98 | class IContextAwareDefaultFactory(zope.interface.Interface):
99 | def __call__(context: Any) -> None: ...
100 |
101 | class IBeforeObjectAssignedEvent(zope.interface.Interface):
102 | object: Any = ...
103 | name: Any = ...
104 | context: Any = ...
105 |
106 | class IValidatable(zope.interface.Interface):
107 | def validate(value: Any) -> None: ...
108 |
109 | class NO_VALUE: ...
110 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_compat.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._compat (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 |
7 | PY3: Any
8 | PY2: Any
9 | string_types: Any
10 | text_type = str
11 | binary_type = bytes
12 | integer_types: Any
13 |
14 | def non_native_string(x: Any): ...
15 | def make_binary(x: Any): ...
16 | text_type = unicode
17 | binary_type = str
18 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_field.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._field (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.schema._bootstrapfields import Field as Field, Bool as Bool, TextLine as TextLine, Complex as Complex, Int as Int, Real as Real, Object as Object
7 | from zope.schema._bootstrapfields import Iterable as Iterable, MinMaxLen as MinMaxLen, Number as Number, Orderable as Orderable, Text as Text
8 | from zope.schema.interfaces import ValidationError
9 |
10 | __docformat__: str
11 |
12 | class SourceText(Text):
13 | __doc__: Any = ...
14 |
15 | class Bytes(MinMaxLen, Field):
16 | __doc__: Any = ...
17 | def fromUnicode(self, value: Any): ...
18 | def fromBytes(self, value: Any): ...
19 |
20 | class NativeString(Text):
21 | def fromBytes(self, value: Any): ...
22 |
23 | class ASCII(NativeString):
24 | __doc__: Any = ...
25 |
26 | class BytesLine(Bytes):
27 | def constraint(self, value: Any): ...
28 |
29 | class NativeStringLine(TextLine):
30 | def fromBytes(self, value: Any): ...
31 |
32 | class ASCIILine(ASCII):
33 | __doc__: Any = ...
34 | def constraint(self, value: Any): ...
35 |
36 | class InvalidFloatLiteral(ValueError, ValidationError): ...
37 | class Float(Real): ...
38 | class InvalidDecimalLiteral(ValueError, ValidationError): ...
39 | class Decimal(Number): ...
40 |
41 | class Datetime(Orderable, Field):
42 | __doc__: Any = ...
43 | def __init__(self, *args: Any, **kw: Any) -> None: ...
44 |
45 | class Date(Orderable, Field):
46 | __doc__: Any = ...
47 |
48 | class Timedelta(Orderable, Field):
49 | __doc__: Any = ...
50 |
51 | class Time(Orderable, Field):
52 | __doc__: Any = ...
53 |
54 | class MissingVocabularyError(ValidationError, ValueError, LookupError): ...
55 |
56 | class InvalidVocabularyError(ValidationError, ValueError, TypeError):
57 | def __init__(self, vocabulary: Any) -> None: ...
58 |
59 | class Choice(Field):
60 | vocabulary: Any = ...
61 | vocabularyName: Any = ...
62 | def __init__(self, values: Optional[Any] = ..., vocabulary: Optional[Any] = ..., source: Optional[Any] = ..., **kw: Any) -> None: ...
63 | source: Any = ...
64 | def bind(self, context: Any): ...
65 | def fromUnicode(self, value: Any): ...
66 |
67 | class _StrippedNativeStringLine(NativeStringLine):
68 | def fromUnicode(self, value: Any): ...
69 | def fromBytes(self, value: Any): ...
70 |
71 | class URI(_StrippedNativeStringLine): ...
72 | class PythonIdentifier(_StrippedNativeStringLine): ...
73 |
74 | class DottedName(_StrippedNativeStringLine):
75 | min_dots: Any = ...
76 | max_dots: Any = ...
77 | def __init__(self, *args: Any, **kw: Any) -> None: ...
78 |
79 | class Id(_StrippedNativeStringLine): ...
80 |
81 | class InterfaceField(Field):
82 | __doc__: Any = ...
83 |
84 | class Collection(MinMaxLen, Iterable):
85 | value_type: Any = ...
86 | unique: bool = ...
87 | def __init__(self, value_type: Any = ..., unique: Any = ..., **kw: Any) -> None: ...
88 | def bind(self, context: Any): ...
89 | AbstractCollection = Collection
90 |
91 | class Sequence(Collection): ...
92 | class Tuple(Sequence): ...
93 | class MutableSequence(Sequence): ...
94 | class List(MutableSequence): ...
95 |
96 | class _AbstractSet(Collection):
97 | unique: bool = ...
98 | def __init__(self, *args: Any, **kwargs: Any) -> None: ...
99 |
100 | class Set(_AbstractSet): ...
101 | class FrozenSet(_AbstractSet): ...
102 |
103 | class Mapping(MinMaxLen, Iterable):
104 | key_type: Any = ...
105 | value_type: Any = ...
106 | def __init__(self, key_type: Optional[Any] = ..., value_type: Optional[Any] = ..., **kw: Any) -> None: ...
107 | def bind(self, object: Any): ...
108 |
109 | class MutableMapping(Mapping): ...
110 | class Dict(MutableMapping): ...
111 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_messageid.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._messageid (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/_schema.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema._schema (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any
6 | from zope.schema._bootstrapfields import getFields as getFields
7 |
8 | def getFieldNames(schema: Any): ...
9 | def getFieldsInOrder(schema: Any, _field_key: Any = ...): ...
10 | def getFieldNamesInOrder(schema: Any): ...
11 | def getValidationErrors(schema: Any, value: Any): ...
12 | def getSchemaValidationErrors(schema: Any, value: Any): ...
13 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/accessors.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema.accessors (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface.interface import Method
7 |
8 | class FieldReadAccessor(Method):
9 | def __provides__(self): ...
10 | __provides__: Any = ...
11 | field: Any = ...
12 | __doc__: Any = ...
13 | def __init__(self, field: Any) -> None: ...
14 | def getSignatureString(self): ...
15 | def getSignatureInfo(self): ...
16 | def get(self, object: Any): ...
17 | def query(self, object: Any, default: Optional[Any] = ...): ...
18 | def set(self, object: Any, value: Any) -> None: ...
19 | def __getattr__(self, name: Any): ...
20 | def bind(self, object: Any): ...
21 |
22 | class FieldWriteAccessor(Method):
23 | field: Any = ...
24 | __doc__: Any = ...
25 | def __init__(self, field: Any) -> None: ...
26 | def getSignatureString(self): ...
27 | def getSignatureInfo(self): ...
28 |
29 | def accessors(field: Any) -> None: ...
30 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/fieldproperty.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema.fieldproperty (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 |
7 | class FieldUpdatedEvent:
8 | inst: Any = ...
9 | field: Any = ...
10 | old_value: Any = ...
11 | new_value: Any = ...
12 | def __init__(self, inst: Any, field: Any, old_value: Any, new_value: Any) -> None: ...
13 |
14 | class FieldProperty:
15 | def __init__(self, field: Any, name: Optional[Any] = ...) -> None: ...
16 | def __get__(self, inst: Any, klass: Any): ...
17 | def queryValue(self, inst: Any, default: Any): ...
18 | def __set__(self, inst: Any, value: Any) -> None: ...
19 | def __getattr__(self, name: Any): ...
20 |
21 | def createFieldProperties(schema: Any, omit: Any = ...) -> None: ...
22 |
23 | class FieldPropertyStoredThroughField:
24 | field: Any = ...
25 | def __init__(self, field: Any, name: Optional[Any] = ...) -> None: ...
26 | def setValue(self, inst: Any, field: Any, value: Any) -> None: ...
27 | def getValue(self, inst: Any, field: Any): ...
28 | def queryValue(self, inst: Any, field: Any, default: Any): ...
29 | def __getattr__(self, name: Any): ...
30 | def __get__(self, inst: Any, klass: Any): ...
31 | def __set__(self, inst: Any, value: Any): ...
32 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/interfaces.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema.interfaces (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 | from zope.interface import Interface
7 | from zope.interface.common.mapping import IEnumerableMapping
8 | from zope.schema._bootstrapinterfaces import ConstraintNotSatisfied as ConstraintNotSatisfied, IBeforeObjectAssignedEvent as IBeforeObjectAssignedEvent, IContextAwareDefaultFactory as IContextAwareDefaultFactory, IFromBytes as IFromBytes, IFromUnicode as IFromUnicode, IValidatable, InvalidValue as InvalidValue, LenOutOfBounds as LenOutOfBounds, NotAContainer as NotAContainer, NotAnInterface as NotAnInterface, NotAnIterator as NotAnIterator, OrderableOutOfBounds as OrderableOutOfBounds, OutOfBounds as OutOfBounds, RequiredMissing as RequiredMissing, SchemaNotCorrectlyImplemented as SchemaNotCorrectlyImplemented, SchemaNotFullyImplemented as SchemaNotFullyImplemented, SchemaNotProvided as SchemaNotProvided, StopValidation as StopValidation, TooBig as TooBig, TooLong as TooLong, TooShort as TooShort, TooSmall as TooSmall, ValidationError as ValidationError, WrongContainedType as WrongContainedType, WrongType as WrongType
9 |
10 | class NotUnique(ValidationError):
11 | __doc__: Any = ...
12 |
13 | class InvalidURI(ValidationError):
14 | __doc__: Any = ...
15 |
16 | class InvalidId(ValidationError):
17 | __doc__: Any = ...
18 |
19 | class InvalidDottedName(ValidationError):
20 | __doc__: Any = ...
21 |
22 | class Unbound(Exception):
23 | __doc__: Any = ...
24 |
25 | class IField(IValidatable):
26 | def bind(object: Any) -> None: ...
27 | title: Any = ...
28 | description: Any = ...
29 | required: Any = ...
30 | readonly: Any = ...
31 | default: Any = ...
32 | missing_value: Any = ...
33 | order: Any = ...
34 | def constraint(value: Any) -> None: ...
35 | def validate(value: Any) -> None: ...
36 | def get(object: Any) -> None: ...
37 | def query(object: Any, default: Optional[Any] = ...) -> None: ...
38 | def set(object: Any, value: Any) -> None: ...
39 |
40 | class IIterable(IField): ...
41 | class IContainer(IField): ...
42 | class IOrderable(IField): ...
43 | class ILen(IField): ...
44 |
45 | class IMinMax(IOrderable):
46 | min: Any = ...
47 | max: Any = ...
48 |
49 | class IMinMaxLen(ILen):
50 | min_length: Any = ...
51 | max_length: Any = ...
52 |
53 | class IInterfaceField(IField): ...
54 |
55 | class IBool(IField):
56 | default: Any = ...
57 |
58 | class IBytes(IMinMaxLen, IIterable, IField): ...
59 | class IText(IMinMaxLen, IIterable, IField): ...
60 | class INativeString: ...
61 | class IASCII(INativeString): ...
62 | class IBytesLine(IBytes): ...
63 | class IASCIILine(IASCII): ...
64 | class ISourceText(IText): ...
65 | class ITextLine(IText): ...
66 | class INativeStringLine: ...
67 | class IPassword(ITextLine): ...
68 |
69 | class INumber(IMinMax, IField):
70 | min: Any = ...
71 | max: Any = ...
72 | default: Any = ...
73 |
74 | class IComplex(INumber):
75 | min: Any = ...
76 | max: Any = ...
77 | default: Any = ...
78 |
79 | class IReal(IComplex):
80 | min: Any = ...
81 | max: Any = ...
82 | default: Any = ...
83 |
84 | class IRational(IReal):
85 | min: Any = ...
86 | max: Any = ...
87 | default: Any = ...
88 |
89 | class IIntegral(IRational):
90 | min: Any = ...
91 | max: Any = ...
92 | default: Any = ...
93 |
94 | class IInt(IIntegral):
95 | min: Any = ...
96 | max: Any = ...
97 | default: Any = ...
98 |
99 | class IFloat(IReal): ...
100 | class IDecimal(INumber): ...
101 | class IDatetime(IMinMax, IField): ...
102 | class IDate(IMinMax, IField): ...
103 | class ITimedelta(IMinMax, IField): ...
104 | class ITime(IMinMax, IField): ...
105 | class IURI(INativeStringLine): ...
106 | class IId(INativeStringLine): ...
107 |
108 | class IDottedName(INativeStringLine):
109 | min_dots: Any = ...
110 | max_dots: Any = ...
111 |
112 | class IPythonIdentifier(INativeStringLine): ...
113 |
114 | class IChoice(IField):
115 | vocabulary: Any = ...
116 | vocabularyName: Any = ...
117 |
118 | class ICollection(IMinMaxLen, IIterable, IContainer):
119 | value_type: Any = ...
120 | unique: Any = ...
121 |
122 | class ISequence(ICollection): ...
123 | class IMutableSequence(ISequence): ...
124 | class IUnorderedCollection(ICollection): ...
125 |
126 | class IAbstractSet(IUnorderedCollection):
127 | unique: Any = ...
128 |
129 | class IAbstractBag(IUnorderedCollection):
130 | unique: Any = ...
131 |
132 | class ITuple(ISequence): ...
133 | class IList(IMutableSequence): ...
134 | class ISet(IAbstractSet): ...
135 | class IFrozenSet(IAbstractSet): ...
136 |
137 | class IObject(IField):
138 | schema: Any = ...
139 | validate_invariants: Any = ...
140 |
141 | class IMapping(IMinMaxLen, IIterable, IContainer):
142 | key_type: Any = ...
143 | value_type: Any = ...
144 |
145 | class IMutableMapping(IMapping): ...
146 | class IDict(IMutableMapping): ...
147 |
148 | class ITerm(Interface):
149 | value: Any = ...
150 |
151 | class ITokenizedTerm(ITerm):
152 | token: Any = ...
153 |
154 | class ITitledTokenizedTerm(ITokenizedTerm):
155 | title: Any = ...
156 |
157 | class ISource(Interface):
158 | def __contains__(value: Any) -> None: ...
159 |
160 | class ISourceQueriables(Interface):
161 | def getQueriables() -> None: ...
162 |
163 | class IContextSourceBinder(Interface):
164 | def __call__(context: Any) -> None: ...
165 |
166 | class IBaseVocabulary(ISource):
167 | def getTerm(value: Any) -> None: ...
168 |
169 | class IIterableSource(ISource):
170 | def __iter__() -> None: ...
171 | def __len__() -> None: ...
172 |
173 | class IIterableVocabulary(Interface):
174 | def __iter__() -> None: ...
175 | def __len__() -> None: ...
176 |
177 | class IVocabulary(IIterableVocabulary, IBaseVocabulary): ...
178 |
179 | class IVocabularyTokenized(IVocabulary):
180 | def getTermByToken(token: Any) -> None: ...
181 |
182 | class ITreeVocabulary(IVocabularyTokenized, IEnumerableMapping): ...
183 |
184 | class IVocabularyRegistry(Interface):
185 | def get(context: Any, name: Any) -> None: ...
186 |
187 | class IVocabularyFactory(Interface):
188 | def __call__(context: Any) -> None: ...
189 |
190 | class IFieldEvent(Interface):
191 | field: Any = ...
192 | object: Any = ...
193 |
194 | class IFieldUpdatedEvent(IFieldEvent):
195 | old_value: Any = ...
196 | new_value: Any = ...
197 |
--------------------------------------------------------------------------------
/src/zope-stubs/schema/vocabulary.pyi:
--------------------------------------------------------------------------------
1 | # Stubs for zope.schema.vocabulary (Python 3.6)
2 | #
3 | # NOTE: This dynamically typed stub was automatically generated by stubgen.
4 |
5 | from typing import Any, Optional
6 |
7 | class SimpleTerm:
8 | value: Any = ...
9 | token: Any = ...
10 | title: Any = ...
11 | def __init__(self, value: Any, token: Optional[Any] = ..., title: Optional[Any] = ...) -> None: ...
12 | def __eq__(self, other: Any): ...
13 | def __ne__(self, other: Any): ...
14 | def __hash__(self): ...
15 |
16 | class SimpleVocabulary:
17 | by_value: Any = ...
18 | by_token: Any = ...
19 | def __init__(self, terms: Any, *interfaces: Any, **kwargs: Any) -> None: ...
20 | @classmethod
21 | def fromItems(cls, items: Any, *interfaces: Any): ...
22 | @classmethod
23 | def fromValues(cls, values: Any, *interfaces: Any): ...
24 | @classmethod
25 | def createTerm(cls, *args: Any): ...
26 | def __contains__(self, value: Any): ...
27 | def getTerm(self, value: Any): ...
28 | def getTermByToken(self, token: Any): ...
29 | def __iter__(self): ...
30 | def __len__(self): ...
31 | def __eq__(self, other: Any): ...
32 | def __ne__(self, other: Any): ...
33 | def __hash__(self): ...
34 |
35 | class TreeVocabulary:
36 | terms_factory: Any = ...
37 | path_by_value: Any = ...
38 | term_by_value: Any = ...
39 | term_by_token: Any = ...
40 | def __init__(self, terms: Any, *interfaces: Any) -> None: ...
41 | def __contains__(self, value: Any): ...
42 | def __getitem__(self, key: Any): ...
43 | def __iter__(self): ...
44 | def __len__(self): ...
45 | def get(self, key: Any, default: Optional[Any] = ...): ...
46 | def keys(self): ...
47 | def values(self): ...
48 | def items(self): ...
49 | @classmethod
50 | def fromDict(cls, dict_: Any, *interfaces: Any): ...
51 | def getTerm(self, value: Any): ...
52 | def getTermByToken(self, token: Any): ...
53 | def getTermPath(self, value: Any): ...
54 |
55 | class VocabularyRegistryError(LookupError):
56 | name: Any = ...
57 | def __init__(self, name: Any) -> None: ...
58 |
59 | class VocabularyRegistry:
60 | def __init__(self) -> None: ...
61 | def get(self, context: Any, name: Any): ...
62 | def register(self, name: Any, factory: Any) -> None: ...
63 |
64 | def getVocabularyRegistry(): ...
65 | def setVocabularyRegistry(registry: Any) -> None: ...
66 |
--------------------------------------------------------------------------------
/tests/samples/adaptation.py:
--------------------------------------------------------------------------------
1 | """A simple valid interface declaration
2 | """
3 | import zope.interface
4 |
5 |
6 | class ISomething(zope.interface.Interface):
7 | def hello(x: int, y: str) -> None:
8 | pass
9 |
10 | @zope.interface.implementer(ISomething)
11 | class AbstractSomething(object):
12 | def thefunc(self) -> None:
13 | pass
14 | pass
15 |
16 | @zope.interface.implementer(ISomething)
17 | class ConcreteSomething(object):
18 | def hello(self, x: int, y: str) -> None:
19 | pass
20 |
21 | class Context(object):
22 | pass
23 |
24 | def main() -> None:
25 | ctx = Context()
26 | smth = ISomething(ctx)
27 | smth.hello(2, 3) # Error: second argument is expected to be string
28 |
29 | asmth = AbstractSomething() # Error, cannot instantiate abstract class
30 |
31 | csmth = ConcreteSomething() # Can instantiate (using default object constructor)
32 |
33 | if __name__ == '__main__':
34 | main()
35 |
36 | """
37 |
41 | """
42 |
--------------------------------------------------------------------------------
/tests/samples/classimplements.py:
--------------------------------------------------------------------------------
1 | from zope.interface import implementer
2 | from zope.interface import Interface
3 | from zope.interface import classImplements
4 |
5 |
6 | class IFoo(Interface):
7 | def foo() -> int:
8 | pass
9 |
10 |
11 | class IBar(Interface):
12 | def bar() -> str:
13 | pass
14 |
15 |
16 | class FooBar:
17 | def foo(self) -> int:
18 | return 0
19 |
20 | def bar(self) -> str:
21 | return ""
22 |
23 |
24 | classImplements(FooBar, IFoo, IBar)
25 |
26 |
27 | foo: IFoo = FooBar()
28 | bar: IBar = FooBar()
29 |
30 |
31 | """
32 |
34 | """
35 |
--------------------------------------------------------------------------------
/tests/samples/classimplements_broken_iface.py:
--------------------------------------------------------------------------------
1 | """Incorrectly implemented interfaces are reported"""
2 |
3 | from zope.interface import implementer
4 | from zope.interface import Interface
5 | from zope.interface import classImplements
6 |
7 | from unknown import IFoo
8 |
9 |
10 | def ImNotAnInterface() -> int:
11 | return 0
12 |
13 | ImNotAnInterfaceEither = "indeed"
14 |
15 | class Foo:
16 | def foo(self) -> int:
17 | return 0
18 |
19 | classImplements(Foo, IFoo, ImNotAnInterface, ImNotAnInterfaceEither, 2+2)
20 |
21 |
22 | """
23 |
32 | """
33 |
--------------------------------------------------------------------------------
/tests/samples/classimplements_broken_impl.py:
--------------------------------------------------------------------------------
1 | """Incorrectly implemented interfaces are reported"""
2 |
3 | from zope.interface import implementer
4 | from zope.interface import Interface
5 | from zope.interface import classImplements
6 |
7 | from unknown import Foo
8 |
9 |
10 | class IFoo(Interface):
11 | def foo() -> int:
12 | pass
13 |
14 |
15 | classImplements(Foo, IFoo)
16 |
17 |
18 | """
19 |
24 | """
25 |
--------------------------------------------------------------------------------
/tests/samples/classimplements_wrong.py:
--------------------------------------------------------------------------------
1 | """Incorrectly implemented interfaces are reported"""
2 |
3 | from zope.interface import implementer
4 | from zope.interface import Interface
5 | from zope.interface import classImplements
6 |
7 |
8 | class IFoo(Interface):
9 | def foo() -> int:
10 | pass
11 |
12 |
13 | class Foo:
14 | def bar(self) -> int:
15 | return 0
16 |
17 |
18 | classImplements(Foo, IFoo)
19 |
20 |
21 | foo: IFoo = Foo()
22 |
23 |
24 | """
25 |
28 | """
29 |
--------------------------------------------------------------------------------
/tests/samples/contextmanager.py:
--------------------------------------------------------------------------------
1 | from contextlib import contextmanager
2 | from typing import Iterator, TypeVar, Generic
3 |
4 | _T = TypeVar("_T")
5 |
6 |
7 | class A(Generic[_T]):
8 | pass
9 |
10 | @contextmanager
11 | def m(x: _T) -> Iterator[A[_T]]:
12 | return iter([A()])
13 |
14 |
15 | with m(7) as x:
16 | reveal_type(x)
17 | print(x)
18 |
19 |
20 | """
21 |
24 | """
25 |
--------------------------------------------------------------------------------
/tests/samples/forward_reference_to_implementer.py:
--------------------------------------------------------------------------------
1 | """
2 | Reproduces a bug where MROs were incorrectly computed for implementers
3 | https://github.com/Shoobx/mypy-zope/issues/34
4 | https://github.com/Shoobx/mypy-zope/issues/76
5 | """
6 |
7 | from zope.interface import implementer, Interface
8 |
9 |
10 | class IProtocol(Interface):
11 | pass
12 |
13 |
14 | def main() -> None:
15 | class Factory:
16 | # It seems important for "Protocol" to show up as an attribute annotation to
17 | # trigger the bug(!?)
18 | protocol: "Protocol"
19 |
20 | @implementer(IProtocol)
21 | class Protocol:
22 | pass
23 |
24 |
25 | if __name__ == '__main__':
26 | main()
27 |
28 | """
29 | Expect no errors. A specific test checks that we correct compute the MRO of `Protocol`.
30 |
32 | """
33 |
--------------------------------------------------------------------------------
/tests/samples/forwardref.py:
--------------------------------------------------------------------------------
1 | """Method parameters refers to yet undeclared type
2 | """
3 |
4 | import zope.interface
5 |
6 | class ISomething(zope.interface.Interface):
7 | def hello(thing: "IThing") -> None:
8 | pass
9 |
10 | @zope.interface.implementer(ISomething)
11 | class Something(object):
12 | def hello(self, thing: "IThing") -> None: # Wrong kind of list
13 | print(f"Hello, {thing.get_name()}")
14 | reveal_type(thing)
15 |
16 |
17 | class IThing(zope.interface.Interface):
18 | def get_name() -> str:
19 | pass
20 |
21 | """
22 |
25 | """
26 |
--------------------------------------------------------------------------------
/tests/samples/impl_inheritance.py:
--------------------------------------------------------------------------------
1 | """Interface implementations can be inherited
2 | """
3 | import zope.interface
4 |
5 | class IBookmark(zope.interface.Interface):
6 | def remember(url: str) -> None:
7 | pass
8 |
9 | @zope.interface.implementer(IBookmark)
10 | class Bookmark(object):
11 | pass
12 |
13 |
14 | class SuperBookmark(Bookmark):
15 | pass
16 |
17 |
18 | def main() -> None:
19 | bm: IBookmark = SuperBookmark()
20 |
21 | # We can assign anything to abstract attributes
22 | bm.remember(None) # Error, string is expected
23 |
24 | if __name__ == '__main__':
25 | main()
26 |
27 | """
28 |
32 | """
33 |
--------------------------------------------------------------------------------
/tests/samples/impl_property.py:
--------------------------------------------------------------------------------
1 | """Interface implements attribute as property
2 | """
3 | import zope.interface
4 |
5 |
6 | class IBookmark(zope.interface.Interface):
7 | number: int
8 | text: str
9 |
10 | @zope.interface.implementer(IBookmark)
11 | class Bookmark(object):
12 | @property
13 | def number(self) -> str:
14 | return "hello"
15 |
16 | @number.setter
17 | def number(self, value: str) -> None:
18 | pass
19 |
20 | @property
21 | def text(self) -> int:
22 | return 5
23 |
24 |
25 | def main() -> None:
26 | bm: IBookmark = Bookmark()
27 | bm.number = 12
28 |
29 | """
30 | Properties are not type-checked in current version, so no error output
31 |
33 | """
34 |
--------------------------------------------------------------------------------
/tests/samples/incompatible_signature.py:
--------------------------------------------------------------------------------
1 | """Something.hello has a signature, incompatible with interface
2 | """
3 |
4 | import zope.interface
5 |
6 |
7 | class ISomething(zope.interface.Interface):
8 | def hello(x: int, y: str) -> None:
9 | pass
10 |
11 |
12 | @zope.interface.implementer(ISomething)
13 | class Something(object):
14 | def hello(self, x: int, y: int) -> None:
15 | print(f"X: {x}, Y: {y}")
16 |
17 |
18 | def run(smth: ISomething):
19 | smth.hello(1, "test")
20 |
21 |
22 | def main() -> None:
23 | smth = Something()
24 | run(smth)
25 |
26 |
27 | if __name__ == '__main__':
28 | main()
29 |
30 | """
31 |
36 | """
37 |
--------------------------------------------------------------------------------
/tests/samples/innerclass.py:
--------------------------------------------------------------------------------
1 | """Dynamic subclassing is handled without errors"""
2 |
3 | def decorator(cls):
4 | class SuperClass(cls):
5 | pass
6 |
7 | """
8 |
10 | """
11 |
--------------------------------------------------------------------------------
/tests/samples/interface_annotated_attribute.py:
--------------------------------------------------------------------------------
1 | """zope.interface provides an annotated attribute for classes
2 | """
3 | import typing
4 | import zope.interface
5 |
6 | class IFoo(zope.interface.Interface):
7 | f_str: typing.Text = zope.interface.Attribute("Text Attr")
8 | f_str_opt: typing.Optional[typing.Text] = zope.interface.Attribute("Optional Text Attr")
9 | f_int: int = zope.interface.Attribute("Int Attr")
10 | f_bar: "IBar" = zope.interface.Attribute("Other Intarface Attr")
11 |
12 | class IBar(zope.interface.Interface):
13 | pass
14 |
15 | @zope.interface.implementer(IFoo)
16 | class Foo(object):
17 | f_str = None
18 | f_str_opt = None
19 | f_int = None
20 | f_bar = None
21 |
22 | @zope.interface.implementer(IBar)
23 | class Bar(object):
24 | pass
25 |
26 | def main() -> None:
27 | foo: IFoo = Foo()
28 | bar: IBar = Bar()
29 |
30 | foo.f_str = "Sample"
31 | foo.f_str = 10
32 | foo.f_str = None
33 | foo.f_str_opt = None
34 | foo.f_int = 10
35 | foo.f_bar = bar
36 |
37 | if __name__ == '__main__':
38 | main()
39 |
40 | """
41 |
45 | """
46 |
--------------------------------------------------------------------------------
/tests/samples/interface_attribute.py:
--------------------------------------------------------------------------------
1 | """zope.interface provides an abstract attribute for classes
2 |
3 | It is translated to Any type.
4 | """
5 | import zope.interface
6 |
7 | class IBookmark(zope.interface.Interface):
8 | field = zope.interface.Attribute('Arbitrary Attribute')
9 |
10 |
11 | @zope.interface.implementer(IBookmark)
12 | class Bookmark(object):
13 | field = None
14 |
15 |
16 | def main() -> None:
17 | bm: IBookmark = Bookmark()
18 |
19 | # We can assign anything to abstract attributes
20 | bm.field = 343
21 | bm.field = None
22 | bm.field = "Sample"
23 |
24 | if __name__ == '__main__':
25 | main()
26 |
27 | """
28 |
30 | """
31 |
--------------------------------------------------------------------------------
/tests/samples/interface_fieldproperty.py:
--------------------------------------------------------------------------------
1 | """Interfaces can be introspected by a set of methods"""
2 |
3 | import zope.interface
4 | import zope.schema
5 | from zope.schema.fieldproperty import FieldProperty
6 |
7 | class IBookmark(zope.interface.Interface):
8 | url = zope.schema.TextLine()
9 |
10 |
11 | @zope.interface.implementer(IBookmark)
12 | class Bookmark:
13 | url = FieldProperty(IBookmark['url'])
14 |
15 |
16 | def main() -> None:
17 | bm = Bookmark()
18 | reveal_type(bm.url)
19 | reveal_type(IBookmark.url)
20 | bm.url = 'http'
21 |
22 |
23 | if __name__ == '__main__':
24 | main()
25 |
26 | """
27 | FieldProperty cannot find out the type of the field, unfortunately, so
28 | types of all FieldProeprties are Any. Maybe this will get fixed some day.
29 |
30 |
34 | """
35 |
--------------------------------------------------------------------------------
/tests/samples/interface_getattr.py:
--------------------------------------------------------------------------------
1 | """Interface can define a __getattr__ method
2 | """
3 | import zope.interface
4 |
5 | class IData(zope.interface.Interface):
6 | def __getattr__(name: str) -> int:
7 | pass
8 |
9 | def main() -> None:
10 | data = IData(None)
11 | reveal_type(data.legs)
12 |
13 | """
14 |
17 | """
18 |
--------------------------------------------------------------------------------
/tests/samples/interface_implications.py:
--------------------------------------------------------------------------------
1 | """zope.interface provides an abstract attribute for classes
2 |
3 | It is translated to Any type.
4 | """
5 | import zope.interface
6 | from typing import Optional
7 |
8 | class IBookmark(zope.interface.Interface):
9 | field = zope.interface.Attribute('Arbitrary Attribute')
10 |
11 |
12 | @zope.interface.implementer(IBookmark)
13 | class Bookmark(object):
14 | field = None
15 |
16 | def main(obj: Optional[IBookmark]) -> None:
17 |
18 | if not IBookmark.providedBy(obj):
19 | reveal_type(obj)
20 | else:
21 | reveal_type(obj)
22 | reveal_type(obj)
23 |
24 | cls = obj.__class__
25 | if IBookmark.implementedBy(cls):
26 | reveal_type(cls)
27 | else:
28 | reveal_type(cls)
29 | reveal_type(cls)
30 |
31 | if __name__ == '__main__':
32 | main(Bookmark())
33 |
34 | """
35 |
43 | """
44 |
--------------------------------------------------------------------------------
/tests/samples/interface_inheritance.py:
--------------------------------------------------------------------------------
1 | """Interfaces can be inherited
2 | """
3 | import zope.interface
4 |
5 |
6 | class ISomething(zope.interface.Interface):
7 | def hello(x: int, y: str) -> None:
8 | pass
9 |
10 | class ISuperSomething(ISomething):
11 | def greet(msg: str) -> None:
12 | pass
13 |
14 | class ISomethingSomething(ISuperSomething):
15 | def wink(msg: str) -> None:
16 | pass
17 |
18 | @zope.interface.implementer(ISuperSomething)
19 | class SuperSomething(object):
20 | def hello(self, x: int, y: str) -> None:
21 | print(f"X: {x}, Y: {y}")
22 |
23 | def greet(self, msg) -> None:
24 | print(f"Greetings, {msg}")
25 |
26 | @zope.interface.implementer(ISomethingSomething)
27 | class SomethingSomething(SuperSomething):
28 | def wink(self, msg) -> None:
29 | print(f"{msg} ")
30 |
31 | def run(smth: ISomething):
32 | smth.hello(1, "test")
33 |
34 |
35 | def greet(smth: ISuperSomething):
36 | smth.hello(2, "test 2")
37 | smth.greet("world")
38 |
39 |
40 | def main() -> None:
41 | smth = SuperSomething()
42 | run(smth)
43 |
44 | smthsmth = SomethingSomething()
45 | smthsmth.greet("bob")
46 | smthsmth.wink("susanne")
47 | smthsmth.hello(1, "dude")
48 |
49 | run(smthsmth)
50 |
51 |
52 | if __name__ == '__main__':
53 | main()
54 |
55 | """
56 |
58 | """
59 |
--------------------------------------------------------------------------------
/tests/samples/interface_mapping.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | from zope.interface.common import mapping
3 |
4 | class IBookmarkContainer(mapping.IMapping):
5 | pass
6 |
7 | @zope.interface.implementer(IBookmarkContainer)
8 | class BadContainer(object):
9 | def values(self):
10 | pass
11 |
12 | @zope.interface.implementer(IBookmarkContainer)
13 | class GoodContainer(dict):
14 | pass
15 |
16 |
17 | def main() -> None:
18 | bc: IBookmarkContainer = GoodContainer()
19 | bc['one'] = 1
20 |
21 | if __name__ == '__main__':
22 | main()
23 |
24 | """
25 |
31 | """
32 |
--------------------------------------------------------------------------------
/tests/samples/interface_meta.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | from typing import Type, TypeVar
3 |
4 | T = TypeVar('T', bound='zope.interface.Interface')
5 |
6 |
7 | class IBookmark(zope.interface.Interface):
8 | pass
9 |
10 | def createOb(iface: Type[T]) -> T:
11 | if zope.interface.interfaces.IInterface.providedBy(iface):
12 | pass
13 | return iface(None)
14 |
15 | def main(self) -> None:
16 | bm = createOb(IBookmark)
17 | reveal_type(bm)
18 |
19 | """
20 |
23 | """
24 |
--------------------------------------------------------------------------------
/tests/samples/interface_metaclass.py:
--------------------------------------------------------------------------------
1 | from zope.interface import interface
2 |
3 |
4 | class RemoteInterface(metaclass=interface.InterfaceClass):
5 | pass
6 |
7 |
8 | class Api(RemoteInterface):
9 | def open():
10 | "open something"
11 |
--------------------------------------------------------------------------------
/tests/samples/interface_self.py:
--------------------------------------------------------------------------------
1 | """When someone leaves `self` as a parameter in interface function,
2 | bec more helpful in identifying the issue
3 | """
4 |
5 | import zope.interface
6 |
7 | class IAnimal(zope.interface.Interface):
8 | def say(self) -> None:
9 | pass
10 |
11 | @zope.interface.implementer(IAnimal)
12 | class Cow(object):
13 | def say(self) -> None:
14 | print("Moooo")
15 |
16 | """
17 |
20 | """
21 |
--------------------------------------------------------------------------------
/tests/samples/interface_unknown.py:
--------------------------------------------------------------------------------
1 | """When interface is imported from unknown package (one without stubs),
2 | do not produce errors.
3 | """
4 |
5 | import zope.interface
6 |
7 | from unknown import interfaces
8 |
9 | @zope.interface.implementer(interfaces.IUnknownInterface)
10 | class Bookmark(object):
11 | pass
12 |
13 | def main() -> None:
14 | bm: interfaces.IUnknownInterface = Bookmark()
15 | reveal_type(bm)
16 |
17 |
18 | """
19 |
24 | """
25 |
--------------------------------------------------------------------------------
/tests/samples/interface_unknown_direct.py:
--------------------------------------------------------------------------------
1 | """When interface is imported from unknown package (one without stubs),
2 | do not produce errors. Even if imported directly.
3 | """
4 |
5 | import zope.interface
6 |
7 | from unknown.interfaces import IUnknownInterface
8 |
9 | @zope.interface.implementer(IUnknownInterface)
10 | class Bookmark(object):
11 | pass
12 |
13 | def main() -> None:
14 | bm: IUnknownInterface = Bookmark()
15 | reveal_type(bm)
16 |
17 |
18 | """
19 |
24 | """
25 |
--------------------------------------------------------------------------------
/tests/samples/interface_unknown_inherit.py:
--------------------------------------------------------------------------------
1 | """When interface is imported from unknown package, but is inherited by other,
2 | we cannot recognize it as an interface. So standard mypy rules apply, with
3 | all the extra error messages.
4 | """
5 |
6 | import zope.interface
7 |
8 | from unknown.interfaces import IUnknownInterface
9 |
10 | class IKnownInterface(IUnknownInterface):
11 | def hello():
12 | pass
13 |
14 | @zope.interface.implementer(IKnownInterface)
15 | class Bookmark(object):
16 | pass
17 |
18 |
19 | """
20 |
27 | """
28 |
--------------------------------------------------------------------------------
/tests/samples/multiple_implementer.py:
--------------------------------------------------------------------------------
1 | """zope.interface.implementer accepts multiple interfaces
2 | """
3 | import zope.interface
4 |
5 | class IBookmark(zope.interface.Interface):
6 | def remember(url: str) -> None:
7 | pass
8 |
9 | class IActionalble(zope.interface.Interface):
10 | def follow(times: int):
11 | pass
12 |
13 | @zope.interface.implementer(IBookmark, IActionalble)
14 | class Bookmark(object):
15 | pass
16 |
17 | def main() -> None:
18 | bm1: IBookmark = Bookmark()
19 | bm1.remember(None) # Error, string is expected
20 |
21 | bm2: IActionalble = Bookmark()
22 | bm2.follow("bad number") # Error: integer is expected
23 |
24 | if __name__ == '__main__':
25 | main()
26 |
27 | """
28 |
34 | """
35 |
--------------------------------------------------------------------------------
/tests/samples/multiple_inheritance.py:
--------------------------------------------------------------------------------
1 | """A simple valid interface declaration
2 | """
3 | import zope.interface
4 |
5 |
6 | class IAwesome(zope.interface.Interface):
7 | def sparkle(count: int) -> None: pass
8 |
9 | class IClothing(zope.interface.Interface):
10 | def wear() -> None: pass
11 |
12 | @zope.interface.implementer(IAwesome)
13 | class Awesome:
14 | def sparkle(self, count: int) -> None: pass
15 |
16 | @zope.interface.implementer(IClothing)
17 | class Boots:
18 | def __init__(self, color: str) -> None: pass
19 | def wear(self): pass
20 |
21 | class AwesomeBoots(Awesome, Boots):
22 | pass
23 |
24 | def main() -> None:
25 | myboots = AwesomeBoots(color='red')
26 | myboots.wear()
27 | myboots.sparkle(5)
28 | reveal_type(AwesomeBoots.__init__)
29 |
30 | if __name__ == '__main__':
31 | main()
32 |
33 | """
34 |
37 | """
38 |
--------------------------------------------------------------------------------
/tests/samples/nested_definitions.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 |
3 |
4 | class Host:
5 | class IBookmark(zope.interface.Interface):
6 | def get_url() -> str:
7 | pass
8 |
9 | @zope.interface.implementer(IBookmark)
10 | class Bookmark:
11 | def get_url(self) -> str:
12 | return "http://"
13 |
14 |
15 | bm: Host.IBookmark = Host.Bookmark()
16 | reveal_type(bm)
17 |
18 | """
19 |
22 | """
23 |
--------------------------------------------------------------------------------
/tests/samples/no_arg_method.py:
--------------------------------------------------------------------------------
1 | """Interface contains a method without arguments.
2 |
3 | Mypy should not complain.
4 | """
5 | import zope.interface
6 |
7 |
8 | class ISomething(zope.interface.Interface):
9 | def hello() -> None:
10 | pass
11 |
12 | def add(a, b) -> int:
13 | pass
14 |
15 |
16 | @zope.interface.implementer(ISomething)
17 | class Something(object):
18 | def hello(self) -> None:
19 | print("Hello world!")
20 |
21 | def add(self, a, b):
22 | return a + b
23 |
24 |
25 | def run(smth: ISomething):
26 | smth.hello()
27 | smth.add(2, 4)
28 |
29 |
30 | def main() -> None:
31 | smth = Something()
32 | run(smth)
33 |
34 |
35 | if __name__ == '__main__':
36 | main()
37 |
38 | """
39 |
41 | """
42 |
--------------------------------------------------------------------------------
/tests/samples/not_fully_implemented.py:
--------------------------------------------------------------------------------
1 | """A simple valid interface declaration
2 | """
3 | import zope.interface
4 |
5 |
6 | class ISomething(zope.interface.Interface):
7 | def hello(x: int, y: str) -> None:
8 | pass
9 |
10 |
11 | @zope.interface.implementer(ISomething)
12 | class Something(object):
13 | pass
14 |
15 |
16 | def run(smth: ISomething):
17 | smth.hello(1, "test")
18 |
19 |
20 | def main() -> None:
21 | smth = Something()
22 | run(smth)
23 |
24 |
25 | if __name__ == '__main__':
26 | main()
27 |
28 | """
29 |
32 | """
33 |
--------------------------------------------------------------------------------
/tests/samples/open.py:
--------------------------------------------------------------------------------
1 | reveal_type(open('str'))
2 | reveal_type(open('str', 'rb'))
3 |
4 | """
5 |
9 | """
10 |
--------------------------------------------------------------------------------
/tests/samples/overload.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, Union, List, overload
2 | from zope.interface import Interface, implementer
3 |
4 |
5 | class ISomething(Interface):
6 | @overload
7 | def getStuff(index: int) -> int:
8 | ...
9 |
10 | @overload
11 | def getStuff(index: None = None) -> List[int]:
12 | ...
13 |
14 | def getStuff(index: Optional[int] = None) -> Union[int, List[int]]:
15 | """
16 | A method with an awkwardly typed signature: if called with an
17 | argument, it returns a result; if called without an argument,
18 | it returns a list of results.
19 | """
20 | ...
21 |
22 |
23 | @implementer(ISomething)
24 | class MySomething:
25 | @overload
26 | def getStuff(self, index: int) -> int:
27 | ...
28 |
29 | @overload
30 | def getStuff(self, index: None = None) -> List[int]:
31 | ...
32 |
33 | def getStuff(self, index: Optional[int] = None) -> Union[int, List[int]]:
34 | if index is None:
35 | return [1, 2, 3, 4]
36 | else:
37 | return 42
38 |
39 |
40 | z = MySomething()
41 | i: int = z.getStuff(1)
42 | j: List[int] = z.getStuff()
43 |
44 | z2: ISomething = ISomething(z)
45 | i = z.getStuff(1)
46 | j = z.getStuff()
47 |
48 | reveal_type(z.getStuff)
49 | reveal_type(z2.getStuff)
50 |
51 | """
52 |
56 | """
57 |
--------------------------------------------------------------------------------
/tests/samples/overload_readme.py:
--------------------------------------------------------------------------------
1 | """Overload example from README
2 | """
3 |
4 | from typing import Optional, Union, List, overload
5 | import zope.interface
6 |
7 |
8 | class IAnimal(zope.interface.Interface):
9 | @overload
10 | def say() -> str:
11 | ...
12 |
13 | @overload
14 | def say(count: int) -> List[str]:
15 | ...
16 |
17 | def say(count: Optional[int] = None) -> Union[str, List[str]]:
18 | pass
19 |
20 |
21 | @zope.interface.implementer(IAnimal)
22 | class Cow(object):
23 | @overload
24 | def say(self) -> str:
25 | ...
26 |
27 | @overload
28 | def say(self, count: int) -> List[str]:
29 | ...
30 |
31 | def say(self, count: Optional[int] = None) -> Union[str, List[str]]:
32 | if count is None:
33 | return "Mooo"
34 | return ["Mooo"] * count
35 |
36 | """
37 |
39 | """
40 |
--------------------------------------------------------------------------------
/tests/samples/parameterized_types.py:
--------------------------------------------------------------------------------
1 | """Method parameters is of parameterized type
2 | """
3 |
4 | from typing import List
5 |
6 | import zope.interface
7 |
8 | class ISomething(zope.interface.Interface):
9 | def hello(names: List[str]) -> None:
10 | pass
11 |
12 |
13 | @zope.interface.implementer(ISomething)
14 | class Something(object):
15 | def hello(self, names: List[int]) -> None: # Wrong kind of list
16 | print(f"Hello, {names}")
17 |
18 |
19 | """
20 |
25 | """
26 |
--------------------------------------------------------------------------------
/tests/samples/schema_bool.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | import zope.schema
3 |
4 |
5 | class IBookmark(zope.interface.Interface):
6 | flag = zope.schema.Bool(required=False)
7 |
8 | @zope.interface.implementer(IBookmark)
9 | class Bookmark(object):
10 | flag = True
11 |
12 | def main() -> None:
13 | bm: IBookmark = Bookmark()
14 | bm.flag = 343 # Error, expected to be boolean
15 | bm.flag = None
16 | bm.flag = True
17 |
18 | if __name__ == '__main__':
19 | main()
20 |
21 | """
22 |
25 | """
26 |
--------------------------------------------------------------------------------
/tests/samples/schema_field_outside_inteface.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | import zope.schema
3 |
4 | class Bookmark(object):
5 | # This field is not used inside an interface. It will be treated as
6 | # zope.schema.TextLine type
7 | textline = zope.schema.TextLine(
8 | title='Title',
9 | description='Optional text line',
10 | required=False)
11 |
12 |
13 | def main() -> None:
14 | bm = Bookmark()
15 | bm.textline = "text" # Error, zope.schema.TextLine is expected
16 |
17 | if __name__ == '__main__':
18 | main()
19 |
20 | """
21 |
24 | """
25 |
--------------------------------------------------------------------------------
/tests/samples/schema_number.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | import zope.schema
3 |
4 |
5 | class IBookmark(zope.interface.Interface):
6 | cmpl = zope.schema.Complex(required=False)
7 | real = zope.schema.Real(required=False)
8 | integer = zope.schema.Int(required=False)
9 |
10 |
11 | @zope.interface.implementer(IBookmark)
12 | class Bookmark(object):
13 | cmpl = None
14 | real = None
15 | integer = None
16 |
17 |
18 | def main() -> None:
19 | bm: IBookmark = Bookmark()
20 | bm.cmpl = "str" # Error: number is expected
21 | bm.cmpl = complex(1, 2)
22 | bm.cmpl = 1.2
23 | bm.cmpl = 343
24 | bm.real = complex(1, 2) # Error: real is expected
25 | bm.real = 1.2
26 | bm.real = 343
27 | bm.integer = complex(1, 2) # Error: integer is expected
28 | bm.integer = 1.2 # Error: integer is expected
29 | bm.integer = 343
30 |
31 |
32 | if __name__ == '__main__':
33 | main()
34 |
35 | """
36 |
42 | """
43 |
--------------------------------------------------------------------------------
/tests/samples/schema_text.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | import zope.schema
3 |
4 |
5 | class IBookmark(zope.interface.Interface):
6 | textline = zope.schema.TextLine(
7 | title='Title',
8 | description='Optional text line',
9 | required=False)
10 | reqtextline = zope.schema.TextLine(
11 | title='Title',
12 | description='Implicitly required text line',)
13 | expreqtextline = zope.schema.TextLine(
14 | title='Title',
15 | description='Explicitly required text line',
16 | required=True)
17 | asciiline = zope.schema.ASCIILine(
18 | title='Title',
19 | description='ASCII-only text line',
20 | required=False)
21 |
22 |
23 | @zope.interface.implementer(IBookmark)
24 | class Bookmark(object):
25 | textline = None
26 | reqtextline = None
27 | expreqtextline = None
28 | asciiline = None
29 |
30 |
31 | def main() -> None:
32 | bm: IBookmark = Bookmark()
33 | bm.textline = 343 # Error, expected to be string
34 | bm.reqtextline = None # Error, it is required
35 | bm.expreqtextline = None # Error, it is required
36 | bm.asciiline = True # Error, it is a string
37 |
38 | if __name__ == '__main__':
39 | main()
40 |
41 | """
42 |
48 | """
49 |
--------------------------------------------------------------------------------
/tests/samples/schema_unknown_field.py:
--------------------------------------------------------------------------------
1 | import zope.interface
2 | import zope.schema
3 |
4 | class UnknownField(zope.schema.Field):
5 | """Field is unknown to mypy-test plugin"""
6 |
7 |
8 | class IBookmark(zope.interface.Interface):
9 | field = UnknownField(
10 | title='Unknown',
11 | required=False)
12 |
13 |
14 | @zope.interface.implementer(IBookmark)
15 | class Bookmark(object):
16 | field = None
17 |
18 | def main() -> None:
19 | bm: IBookmark = Bookmark()
20 |
21 | # We can assign anything to unknown fields
22 | bm.field = 343
23 | bm.field = None
24 | bm.field = "Sample"
25 |
26 | if __name__ == '__main__':
27 | main()
28 |
29 | """
30 |
32 | """
--------------------------------------------------------------------------------
/tests/samples/simple_valid.py:
--------------------------------------------------------------------------------
1 | """A simple valid interface declaration
2 | """
3 |
4 | import zope.interface
5 |
6 |
7 | class ISomething(zope.interface.Interface):
8 | def hello(x: int, y: str) -> None:
9 | pass
10 |
11 |
12 | @zope.interface.implementer(ISomething)
13 | class Something(object):
14 | def hello(self, x: int, y: str) -> None:
15 | print(f"X: {x}, Y: {y}")
16 |
17 |
18 | def run(smth: ISomething):
19 | smth.hello(1, "test")
20 |
21 |
22 | def main() -> None:
23 | smth = Something()
24 | run(smth)
25 |
26 |
27 | if __name__ == '__main__':
28 | main()
29 |
30 | """
31 |
33 | """
34 |
--------------------------------------------------------------------------------
/tests/samples/unknown_interface.py:
--------------------------------------------------------------------------------
1 | """When importing an interface from unknown module, we just ignore it
2 | """
3 | import zope.interface
4 |
5 | from unknown import IUnknownInterface
6 |
7 | @zope.interface.implementer(IUnknownInterface)
8 | class Bookmark(object):
9 | flag = True
10 |
11 | def main() -> None:
12 | bm = Bookmark()
13 | bm.flag = False
14 |
15 | if __name__ == '__main__':
16 | main()
17 |
18 | """
19 |
23 | """
24 |
--------------------------------------------------------------------------------
/tests/samples/unknown_metaclass.py:
--------------------------------------------------------------------------------
1 | """When metaclass is not defined, ignore it"""
2 |
3 | from i.dont.exist import MetaKlass
4 |
5 |
6 | class Leg(metaclass=MetaKlass):
7 | pass
8 |
9 |
10 | """
11 |
15 | """
16 |
--------------------------------------------------------------------------------
/tests/test_samples.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 |
4 | import pytest
5 | from mypy import build
6 | from mypy import options
7 | from mypy.errors import CompileError
8 | from mypy.modulefinder import BuildSource
9 |
10 |
11 | HERE = os.path.abspath(os.path.dirname(__file__))
12 | SAMPLES_DIR = os.path.join(HERE, "samples")
13 | OUTPUT_RE = re.compile(r"", re.MULTILINE | re.DOTALL)
14 |
15 |
16 | @pytest.fixture(scope="session")
17 | def mypy_cache_dir(tmp_path_factory):
18 | tdir = tmp_path_factory.mktemp('.mypy_cahe')
19 | print("Setup cache", str(tdir))
20 | return str(tdir)
21 |
22 |
23 | def test_samples(samplefile, mypy_cache_dir):
24 | opts = options.Options()
25 | opts.cache_dir = mypy_cache_dir
26 | opts.show_traceback = True
27 | opts.namespace_packages = True
28 | opts.hide_error_codes = True
29 | opts.plugins = ['mypy_zope:plugin']
30 | opts.python_version = (3, 11)
31 | # Config file is needed to load plugins, it doesn't not exist and is not
32 | # supposed to.
33 | opts.config_file = ' not_existing_config.ini'
34 |
35 | try:
36 | base_dir = os.path.dirname(samplefile)
37 | source = BuildSource(samplefile,
38 | module=None,
39 | text=None,
40 | base_dir=base_dir)
41 | res = build.build(
42 | sources=[source],
43 | options=opts)
44 | except CompileError as e:
45 | assert False, e
46 |
47 | normalized = normalize_errors(res.errors, samplefile)
48 | actual = '\n'.join(normalized)
49 | expected = find_expected_output(samplefile)
50 | assert actual == expected
51 |
52 |
53 | def find_expected_output(filename):
54 | with open(filename, "r") as f:
55 | source = f.read()
56 | m = OUTPUT_RE.search(source)
57 | if not m:
58 | return ""
59 | return m.group(1).strip()
60 |
61 |
62 | def normalize_errors(errors, filename):
63 | cwd = os.getcwd() + os.path.sep
64 | assert filename.startswith(cwd)
65 | relfname = filename[len(cwd):]
66 | basename = os.path.basename(filename)
67 | return [msg.replace(relfname, basename) for msg in errors]
68 |
69 |
70 | def pytest_generate_tests(metafunc):
71 | samples = []
72 | ids = []
73 | for fname in os.listdir(SAMPLES_DIR):
74 | samples.append(os.path.join(SAMPLES_DIR, fname))
75 | name, ext = os.path.splitext(fname)
76 | ids.append(name)
77 |
78 | metafunc.parametrize("samplefile", samples, ids=ids)
79 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [testenv]
2 | commands =
3 | pytest -v --cov src/mypy_zope
4 | mypy src/mypy_zope --strict
5 | usedevelop = True
6 | extras = test
7 |
--------------------------------------------------------------------------------