Skip to content

Retrieve units sorted by [dimension] #2125

Open
@garrosh

Description

@garrosh

Hello you lovely people!

So I wanted to make a simple GUI to convert values with each other. The user selects some type of unit, say 'length', and the interface would then display two comboboxes with the various choices to do the conversion. I had a version working that I made using purpose-built enums.

class UnitCategory(Enum):
    LENGTH = 'length'
    FORCE = 'force'
    PRESSURE = 'pressure'
    DENSITY = 'density'
    MOMENT = 'moment'

class LengthUnits(Enum):
    METER = 'm'
    CENTIMETER = 'cm'
    MILLIMETER = 'mm'
    KILOMETER = 'km'
    INCH = 'in'
    FOOT = 'ft'

class DefaultUnits(Enum):
    LENGTH = 'in'
    FORCE = 'lbf'
    PRESSURE = 'psi'
    DENSITY = 'lbf/in³'
    MOMENT = 'lbf*in'

def get_units_for_category(category):
    units = None
    if category == UnitCategory.LENGTH.value:
        units = LengthUnits
    elif ...
    return units

def get_default_units_index_for_category(category, default = None):
    unit_list = [ureg(unit).units for unit in category]
    print(unit_list)
    if default is None:
        return unit_list.index(DefaultUnits[category].value)
    else:
        default_unit = ureg(f"{default}").units
        return unit_list.index(default_unit)

But then I thought I could just wrap Pint itself, no? I've read through the documentation, looked at members, all these issues, and I think I have to develop something new, but that's surprising to me.

The best option I have so far would be to iterate over UnitRegistry._units, collecting references and then do .is_compatible_with() to get the list of compatible units. Did I miss something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions