Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the python type hinting for a dictionary variable?

Tags:

Let say I have a dictionary stored in the variable 'v':

from typing import Dict  v = { 'height': 5, 'width':14, 'depth': 3 }  result = doSomething( v )  def doSomething( value:Dict[???] ):     #do stuff 

How do I declare the dictionary type in 'doSomething'? Any ideas anyone? Your help is much appreciated :)

like image 931
CodingFrog Avatar asked Oct 01 '18 14:10

CodingFrog


People also ask

How do you type hinting in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

How do you specify variable type in Python?

Specify a Variable Type Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)

What does type () do in Python?

Python has a lot of built-in functions. The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.

Should I use type hinting in Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.


1 Answers

Dict takes two "arguments", the type of its keys and the type of its values. For a dict that maps strings to integers, use

def doSomething(value: Dict[str, int]): 

The documentation could probably be a little more explicit, though.

like image 105
chepner Avatar answered Sep 22 '22 03:09

chepner