Skip to content

Units as method attributes #933

Open
@IvarStefansson

Description

@IvarStefansson

Variables are tagged with units when created in a model. We have been thinking about providing units for parameters (and possibly derived quantities). So far, we have partially implemented this in the documentation. I've been thinking of ways to improve this which would allow automatic parsing. Here's a suggestion using a decorator:

# Define utility function (in material_constants.py)
def add_units(units):  
    """Adds an si_units attribute to a function."""
    def si_unit_decorator(func):
        setattr(func, "si_units", units)
        return func
    return si_unit_decorator

# Illustration of how to apply using residual aperture as example.
# Build on the existing SolidConstants class to avoid redefinition.
class ImprovedSolidConstants(pp.SolidConstants):
    @add_units("m")  # We'd need to decorate each function like this.
    def residual_aperture(self):
        """Residual aperture [m].

        Returns:
            Residual aperture.

        """
        return self.convert_units(
            self.constants["residual_aperture"], 
            self.residual_aperture.si_units)  # This line could be just "m", as in current version

print(ImprovedSolidConstants.residual_aperture.si_units)  # Returns "m" as specified in decorator
my_constants = ImprovedSolidConstants()
my_constants.set_units(pp.Units())
print(my_constants.residual_aperture())  # Returns default value of 0.1

Caveat: Mypy might not be thrilled.

Metadata

Metadata

Labels

enhancementNew feature or request.user groupIssue to be worked on in the internal user group.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions