gumyr / build123d

A python CAD programming library
Apache License 2.0
432 stars 81 forks source link

Consider using `Self` in direct API typing #171

Closed snoyer closed 1 year ago

snoyer commented 1 year ago

Medhods that return transformed copies of shapes are typed as -> Shape, for example:

class Shape(NodeMixin):
    def rotate(self, axis: Axis, angle: float) -> Shape:
        ...
    def translate(self, vector: VectorLike) -> Shape:
        ...
    def scale(self, factor: float) -> Shape:
        ...

This lead to some imprecision in the type inference, for example a Solid will be assumed to be a Shape:

from build123d import Solid
box = Solid.make_box(1,1,1)
bigger_box = box.scale(2) # type is inferred as `Shape`
print(type(bigger_box))   # "<class 'build123d.topology.Solid'>"

Typing the method as -> Self (imported from typing_extensions) seems to correct the issue and produce the correct inference.

Can anyone chime in on whether that looks like the thing to do if they can foresee any undesirable side-effects?

gumyr commented 1 year ago

There is a comment in build_common.py: "In Python 3.11 the return type should be set to Self here to avoid having to recreate this method." so I've been waiting for this functionality. If Self is imported can it be used in 3.9+?

Just tried - nope, doesn't work in 3.9.

snoyer commented 1 year ago

There is a comment in build_common.py

Oops, definitely missed that.

can it be used in 3.9+?

Good point. I have no idea about the status and version requirements of Self from typing vs from typing_extension. My quick experiment was done on 3.10 only. Needs more investigating...

bernhard-42 commented 1 year ago

Seems to be a Python 3.11 feature: https://docs.python.org/3/whatsnew/3.11.html: PEP 673: Self type

Surprised it works on 3.10

snoyer commented 1 year ago

For what it's worth the typing_extensions package (that build123d already uses: typing_extensions >= 4.4.0, <5) claims to backport the newer typing stuff all the way to 3.7; and

from typing_extensions import Self

does not complain in a 3.9 virtual env here

gumyr commented 1 year ago

This is excellent. Maybe I was trying to import from typing not typing_extensions but when imported correctly it seems to work perfectly in 3.9.