-2

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…

2 Answers2

1

Type Hint doesn't raise exception when you assign incorrect type of value. It's currently 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

Ming
  • 479
  • 2
  • 11
-1

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?

tara
  • 31
  • 4