Skip to content

Version 0.16.2: error when parsing unit strings with spaces #259

@juan-g-bonilla

Description

@juan-g-bonilla

Thank you for all your work creating this library!

In previous versions, you could parse a units string in the format " m" (with a leading space).

Python 3.12.8 (main, Dec  6 2024, 00:00:00) [GCC 14.2.1 20240912 (Red Hat 14.2.1-3)] on linux
>>> import quantities
>>> quantities.__version__
'0.16.1'
>>> quantities.quantity.validate_dimensionality(" m")
Dimensionality({meter: 1})

however, the newer version's switch to using ast.parse instead of eval causes errors in this case:

Python 3.12.8 (main, Dec  6 2024, 00:00:00) [GCC 14.2.1 20240912 (Red Hat 14.2.1-3)] on linux
>>> import quantities
>>> quantities.__version__
'0.16.2'
>>> quantities.quantity.validate_dimensionality(" m")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jbonilla/.local/lib/python3.12/site-packages/quantities/quantity.py", line 34, in validate_dimensionality
    return unit_registry[value].dimensionality
           ~~~~~~~~~~~~~^^^^^^^
  File "/home/jbonilla/.local/lib/python3.12/site-packages/quantities/registry.py", line 82, in __getitem__
    return self.__registry[label]
           ~~~~~~~~~~~~~~~^^^^^^^
  File "/home/jbonilla/.local/lib/python3.12/site-packages/quantities/registry.py", line 32, in __getitem__
    tree = ast.parse(string, mode="eval")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/ast.py", line 52, in parse
    return compile(source, filename, mode, flags,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<unknown>", line 1
    m
IndentationError: unexpected indent

Not sure if supporting whitespace around the units was ever intended, but this change caused some issues on our codebase that depended on this behavior. This is also probably related to #256 .

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions