Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve units sorted by [dimension] #2125

Open
garrosh opened this issue Jan 31, 2025 · 0 comments
Open

Retrieve units sorted by [dimension] #2125

garrosh opened this issue Jan 31, 2025 · 0 comments

Comments

@garrosh
Copy link

garrosh commented Jan 31, 2025

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant