0

I have seen people using

def testing(cha: List[Dict]) -> List[List[Dict]])

I would like to know what is this function for and what is the "->" for? I understand that it take the dictionary with value "cha" which is in list of dictionaries and convert it to list list of dictionaries.

Is my understanding above a correct one? If no, could someone please show me some simple example?

JJson
  • 233
  • 1
  • 4
  • 18
  • What language is this? You tagged Python, but I've never seen Python code like this – Joel Sep 06 '18 at 04:31
  • You can refer from here. https://docs.python.org/3/library/typing.html. Thanks for reply. – JJson Sep 06 '18 at 04:33
  • It's an optional feature in Python 3 to specify the argument types and return type, so the interpreter can make better optimizations. – John Gordon Sep 06 '18 at 04:34
  • @JohnGordon Thank you but could you give me some examples so that I could understand more? I still could not get it from the explanations you shared. I am sorry – JJson Sep 06 '18 at 04:37
  • I'd suggest [mypy getting started](https://mypy.readthedocs.io/en/latest/getting_started.html) -- this is syntax to annotate function types such that you can use a static type checker. – anthony sottile Sep 06 '18 at 04:50
  • Thank you for the suggestion but since I wanted to learn more so I really wish to understand this library method and if possible, I hope someone could show me some simple example. – JJson Sep 06 '18 at 04:54

1 Answers1

2

That is Python's type hinting. It's just syntactic sugar to help the developer reading your code get a sense of what type of input your function is expecting and what type of output it should return. Types to the left of -> denote the input type, and types to the right of -> denote the return type. In your example,

def testing(cha: List[Dict]) -> List[List[Dict]]:
    ...

testing is a function that is supposed to accept a list named cha which contains dictionaries and return a list which contains lists which in turn contain dictionaries. Something like this,

>>> testing([{'a':12, 'b':34}])
>> [[{'a':12, 'b':34}], [{'a':24, 'b':68}]]

That being said, Python is still a dynamically typed language and type hints don't add any compiler optimizations to your code. All type checking still happens at runtime. There is nothing stopping you from violating type hints of your function, which means I could pass any type of argument to testing and it would still try to use it as valid input.

prithajnath
  • 2,000
  • 14
  • 17
  • 1
    Now i get it. So its just a hint. I thought it was some kind of a function to change it to the return types. Thank you so much – JJson Sep 06 '18 at 05:41