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

Don't allow float(quantity) and int(quantity) #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

twmr
Copy link
Contributor

@twmr twmr commented Aug 25, 2017

No description provided.

@apdavison
Copy link
Contributor

Please can you explain the motivation behind this pull request?

@twmr
Copy link
Contributor Author

twmr commented Aug 30, 2017

Sure, the problem is that float(quantity) returns a float, which is a bit surprising.

With my commit you'll get an exception if you do print("%f" % quantity). I think this is better than implicitly stripping the unit in float(quantity).

@apdavison
Copy link
Contributor

I guess I don't see it as surprising or implicit; float(quantity) is explicitly asking to discard the units, and retain only the value in the current units, i.e. very similar to quantity.magnitude.

Does anyone else have an opinion on this?

@bjodah
Copy link
Contributor

bjodah commented Jan 23, 2018

I can see arguments both for and against.
I would propose making the stricter behaviour proposed here opt-in through an environment variable (e.g. QUANTITIES_STRICT=1), even though that would essentially be akin to a module level global variable. Otherwise there need to be a context object being moved around.

But even then this patch should be updated to allow conversions to float when the dimensionality is quantitites.dimensionless, right now it does not (on this branch):

>>> float((3*pq.m/pq.km).rescale(pq.dimensionless))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/bjorn/vc/python-quantities/quantities/quantity.py", line 417, in __float__
    raise TypeError("Quantities can't be converted to floats")
TypeError: Quantities can't be converted to floats

@K3UL
Copy link

K3UL commented Feb 19, 2020

I also do not find any surprise in having float(anything) returning a float. I actually NEED this to happen whenever I am doing some billing. Like we have a rate of x euros per kWh and so I need to do € * kWh = €.

I think @bjodah's suggestion makes some sense, but I still don't see why I could not do float() and just get the value part, stripped of its unit.

@bjodah
Copy link
Contributor

bjodah commented Feb 19, 2020

@K3UL my point is that there's already .magnitude.

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

Successfully merging this pull request may close these issues.

None yet

4 participants