Skip to content

Fix 'typing' import collisions. #581

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/betterproto/compile/importing.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def get_type_reference(
if unwrap:
if source_type in WRAPPER_TYPES:
wrapped_type = type(WRAPPER_TYPES[source_type]().value)
return f"Optional[{wrapped_type.__name__}]"
return f"typing.Optional[{wrapped_type.__name__}]"

if source_type == ".google.protobuf.Duration":
return "timedelta"
Expand Down
17 changes: 8 additions & 9 deletions src/betterproto/plugin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
reference to `A` to `B`'s `fields` attribute.
"""


import builtins
import re
import textwrap
Expand Down Expand Up @@ -319,7 +318,7 @@ def py_name(self) -> str:
@property
def annotation(self) -> str:
if self.repeated:
return f"List[{self.py_name}]"
return f"typing.List[{self.py_name}]"
return self.py_name

@property
Expand Down Expand Up @@ -438,11 +437,11 @@ def datetime_imports(self) -> Set[str]:
def typing_imports(self) -> Set[str]:
imports = set()
annotation = self.annotation
if "Optional[" in annotation:
if "typing.Optional[" in annotation:
imports.add("Optional")
if "List[" in annotation:
if "typing.List[" in annotation:
imports.add("List")
if "Dict[" in annotation:
if "typing.Dict[" in annotation:
imports.add("Dict")
return imports

Expand Down Expand Up @@ -488,7 +487,7 @@ def optional(self) -> bool:
@property
def mutable(self) -> bool:
"""True if the field is a mutable type, otherwise False."""
return self.annotation.startswith(("List[", "Dict["))
return self.annotation.startswith(("typing.List[", "typing.Dict["))

@property
def field_type(self) -> str:
Expand Down Expand Up @@ -573,9 +572,9 @@ def annotation(self) -> str:
if self.use_builtins:
py_type = f"builtins.{py_type}"
if self.repeated:
return f"List[{py_type}]"
return f"typing.List[{py_type}]"
if self.optional:
return f"Optional[{py_type}]"
return f"typing.Optional[{py_type}]"
return py_type


Expand Down Expand Up @@ -645,7 +644,7 @@ def field_type(self) -> str:

@property
def annotation(self) -> str:
return f"Dict[{self.py_k_type}, {self.py_v_type}]"
return f"typing.Dict[{self.py_k_type}, {self.py_v_type}]"

@property
def repeated(self) -> bool:
Expand Down
19 changes: 9 additions & 10 deletions src/betterproto/templates/template.py.j2
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ from datetime import {% for i in output_file.datetime_imports|sort %}{{ i }}{% i

{% endif%}
{% if output_file.typing_imports %}
from typing import {% for i in output_file.typing_imports|sort %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %}

import typing
{% endif %}

{% if output_file.pydantic_imports %}
Expand Down Expand Up @@ -116,14 +115,14 @@ class {{ service.py_name }}Stub(betterproto.ServiceStub):
{%- if method.py_input_message -%}, {{ method.py_input_message_param }}: "{{ method.py_input_message_type }}"{%- endif -%}
{%- else -%}
{# Client streaming: need a request iterator instead #}
, {{ method.py_input_message_param }}_iterator: Union[AsyncIterable["{{ method.py_input_message_type }}"], Iterable["{{ method.py_input_message_type }}"]]
, {{ method.py_input_message_param }}_iterator: typing.Union[typing.AsyncIterable["{{ method.py_input_message_type }}"], typing.Iterable["{{ method.py_input_message_type }}"]]
{%- endif -%}
,
*
, timeout: Optional[float] = None
, deadline: Optional["Deadline"] = None
, metadata: Optional["MetadataLike"] = None
) -> {% if method.server_streaming %}AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
, timeout: typing.Optional[float] = None
, deadline: typing.Optional["Deadline"] = None
, metadata: typing.Optional["MetadataLike"] = None
) -> {% if method.server_streaming %}typing.AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
{% if method.comment %}
{{ method.comment }}

Expand Down Expand Up @@ -191,9 +190,9 @@ class {{ service.py_name }}Base(ServiceBase):
{%- if method.py_input_message -%}, {{ method.py_input_message_param }}: "{{ method.py_input_message_type }}"{%- endif -%}
{%- else -%}
{# Client streaming: need a request iterator instead #}
, {{ method.py_input_message_param }}_iterator: AsyncIterator["{{ method.py_input_message_type }}"]
, {{ method.py_input_message_param }}_iterator: typing.AsyncIterator["{{ method.py_input_message_type }}"]
{%- endif -%}
) -> {% if method.server_streaming %}AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
) -> {% if method.server_streaming %}typing.AsyncIterator["{{ method.py_output_message_type }}"]{% else %}"{{ method.py_output_message_type }}"{% endif %}:
{% if method.comment %}
{{ method.comment }}

Expand Down Expand Up @@ -225,7 +224,7 @@ class {{ service.py_name }}Base(ServiceBase):

{% endfor %}

def __mapping__(self) -> Dict[str, grpclib.const.Handler]:
def __mapping__(self) -> typing.Dict[str, grpclib.const.Handler]:
return {
{% for method in service.methods %}
"{{ method.route }}": grpclib.const.Handler(
Expand Down
18 changes: 9 additions & 9 deletions tests/test_get_ref_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,15 @@ def test_reference_google_wellknown_types_non_wrappers_pydantic(
@pytest.mark.parametrize(
["google_type", "expected_name"],
[
(".google.protobuf.DoubleValue", "Optional[float]"),
(".google.protobuf.FloatValue", "Optional[float]"),
(".google.protobuf.Int32Value", "Optional[int]"),
(".google.protobuf.Int64Value", "Optional[int]"),
(".google.protobuf.UInt32Value", "Optional[int]"),
(".google.protobuf.UInt64Value", "Optional[int]"),
(".google.protobuf.BoolValue", "Optional[bool]"),
(".google.protobuf.StringValue", "Optional[str]"),
(".google.protobuf.BytesValue", "Optional[bytes]"),
(".google.protobuf.DoubleValue", "typing.Optional[float]"),
(".google.protobuf.FloatValue", "typing.Optional[float]"),
(".google.protobuf.Int32Value", "typing.Optional[int]"),
(".google.protobuf.Int64Value", "typing.Optional[int]"),
(".google.protobuf.UInt32Value", "typing.Optional[int]"),
(".google.protobuf.UInt64Value", "typing.Optional[int]"),
(".google.protobuf.BoolValue", "typing.Optional[bool]"),
(".google.protobuf.StringValue", "typing.Optional[str]"),
(".google.protobuf.BytesValue", "typing.Optional[bytes]"),
],
)
def test_referenceing_google_wrappers_unwraps_them(
Expand Down