fix: Decorated target not directly callable

This commit is contained in:
Leni Aniva 2024-07-04 00:24:14 -07:00
parent 6201683c00
commit 46161ba82e
Signed by: aniva
GPG Key ID: 4D9B1C8D10EA4C50
1 changed files with 14 additions and 8 deletions

View File

@ -6,8 +6,9 @@ output objects with the `@target` decorator
""" """
from pathlib import Path from pathlib import Path
from typing import Union from typing import Union
import cadquery as Cq from functools import wraps
from colorama import Fore, Style from colorama import Fore, Style
import cadquery as Cq
class Target: class Target:
@ -16,6 +17,8 @@ class Target:
name: str): name: str):
self._method = method self._method = method
self.name = name self.name = name
def __str__(self):
return f"<target {self.name}>"
def __call__(self, obj, *args, **kwargs): def __call__(self, obj, *args, **kwargs):
return self._method(obj, *args, **kwargs) return self._method(obj, *args, **kwargs)
@ -27,17 +30,21 @@ class Target:
def g(): def g():
for name in dir(subject): for name in dir(subject):
method = getattr(subject, name) method = getattr(subject, name)
if isinstance(method, Target): if hasattr(method, 'target'):
yield name, method yield method.target
return {name: method for name, method in g()} return {method.name: method for method in g()}
def target(name, **kwargs): def target(name, **deco_kwargs):
""" """
Decorator for annotating a build output Decorator for annotating a build output
""" """
def f(method): def f(method):
return Target(method, name=name, **kwargs) @wraps(method)
def wrapper(self, *args, **kwargs):
return method(self, *args, **kwargs)
wrapper.target = Target(method, name, **deco_kwargs)
return wrapper
return f return f
def _to_shape(x: Union[Cq.Workplane, Cq.Shape, Cq.Compound, Cq.Assembly]) -> Cq.Shape: def _to_shape(x: Union[Cq.Workplane, Cq.Shape, Cq.Compound, Cq.Assembly]) -> Cq.Shape:
@ -74,8 +81,7 @@ class Model:
model = f(self) model = f(self)
if verbose >= 1: if verbose >= 1:
print(f"{Fore.BLUE}Building{Style.RESET_ALL} {output_file}", end="") print(f"{Fore.BLUE}Building{Style.RESET_ALL} {output_file}")
_to_shape(model).exportStl(str(output_file)) _to_shape(model).exportStl(str(output_file))
if verbose >= 1: if verbose >= 1:
print("\r", end="")
print(f"{Fore.GREEN}Built{Style.RESET_ALL} {output_file}") print(f"{Fore.GREEN}Built{Style.RESET_ALL} {output_file}")