Wemake-python-styleguide: Forbid float as key/index

Created on 9 Oct 2019  路  6Comments  路  Source: wemake-services/wemake-python-styleguide

Rule request

Thesis

For lists/tuples float as key produces TypeError:

a = [1,2,3]
a[1] # 2
a[1.] # TypeError: list indices must be integers or slices, not float

For dicts float is a bad idea because of accuracy:

b = {.3: 3}
b[.3] # 3
b[.1 + .2] # KeyError: 0.30000000000000004

So, let's catch simple cases:

a[2.0]
a[b / c]  # use a[b // c] instead

Reasoning

The motivation is the same as in #739. Let's detect as many runtime errors statically as possible.

Hacktoberfest help wanted starter rule request

All 6 comments

Well, I would say that this is not actually a type error. That's a best practice: don't use floats as key, it will hurt you. So, I am all for it!

In the case of sequences, it's TypeError. In the case of maps, it's dangerous. In both cases, it's bad after all.

I guess we should forbid setting and getting float keys. That's what should be checked:

some_map = {0.1: 'a'}  # violation!

I can try out this

You are welcome! @abyss143

The only difference in the implementation is that we don't eval +, -, etc. Yet.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sobolevn picture sobolevn  路  3Comments

serhii73 picture serhii73  路  3Comments

sobolevn picture sobolevn  路  4Comments

webknjaz picture webknjaz  路  3Comments

sobolevn picture sobolevn  路  5Comments