gumyr / build123d

A python CAD programming library
Apache License 2.0
395 stars 72 forks source link

build_common's _get_context class method should raise a specific `NoContextError` exception #394

Open gumyr opened 7 months ago

gumyr commented 7 months ago

With a specific exception, methods like _vector_add_sub_wrapper could check for this to improve exception handling.

Created from:

                # TODO make a specific `NoContextError` and raise that from `_get_context()` ?
snoyer commented 7 months ago

In addition to more precise exception handling this would also allow for improvements to the following type of pattern where _get_context() is called multiple times:

if foo._get_context() is None:
    do_something_with_no_context()
else:
    do_something_with_context(foo._get_context())

which could become:

try:
    do_something_with_context(foo._get_context())
except NoContextError:
    do_something_with_no_context()

as per python's EAFP principle.

It is actually what is being done in _vector_add_sub_wrapper (where that #TODO is originally from) by catching AttributeError instead and hoping/assuming it does actually come from _get_context() https://github.com/gumyr/build123d/blob/b18af27e13ee46f85da67f0073a81415a33a06c1/src/build123d/build_common.py#L1228-L1234