Skip to content

Issue with use of typing.cast in get_wt_fraction #4492

@CompRhys

Description

@CompRhys

Python version

py312

Pymatgen version

latest

Operating system version

macos

Current behavior

def get_wt_fraction(self, el: SpeciesLike) -> float:
        """Calculate weight fraction of an Element or Species.

        Args:
            el (Element | Species): Element or Species to get fraction for.

        Returns:
            float: Weight fraction for element el in Composition.
        """
        el_mass = cast("float", get_el_sp(el).atomic_mass)
        return el_mass * abs(self[el]) / self.weight

the typing cast here doesn't change the output to float it's still a float with unit and that caused a serialization error for us in a downstream third party library as we passed a dict of wt_fractions expecting them to be floats from the type hint.

Expected Behavior

It should either be typed as FloatwithUnit or be converted to a float.

Minimal example

Relevant files to reproduce this bug

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions