简体   繁体   中英

Reference position of index without value

As of Python 3, you can explicitly declare variables by type:

x: int = 3
or:
def f(x: int):
    return x

How would I do this with index numbers?

I am trying to maintain the address of the value without calculating the value directly…

Is this how you want it?

x = [3]

a= x.index(3)

print (a)

which outputs 0

the int is not neccessary actually, and what is the or for?

Type Hint doesn't raise exception when you assign incorrect type of value. It's currently the only known for documentation. See in this question: https://stackoverflow.com/a/44282299/8170215

Still, if you wish to define the type hint for dictionary, you can do:

from typing import Dict

x: Dict[int, str] = {1: 'a', 2: 'b'}

which doesn't raise exception when you assign something like x = 'some string' or x['a'] = 'b'

If you want python to raise AssertionError, you can use:

# No exception
x = {1: 'a', 2: 'b'}
assert all(isinstance(key, int) for key in x)

# AssertionError
x = {'a': 'a', 2: 'b'}
assert all(isinstance(key, int) for key in x)

Or, you can use libraries like pydantic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM