Dict from typing library [duplicate] - python

This question already has answers here:
What are type hints in Python 3.5?
(5 answers)
Closed 4 years ago.
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?

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.

Related

Why does type() on an empty list & set yield different answers when compared to keywords 'list' and 'set' using 'is'? [duplicate]

This question already has answers here:
Empty set literal?
(7 answers)
Closed 1 year ago.
I am currently learning Python and was answering questions on a practice quiz where I encountered the following questions:
What is the output of print(type({}) is set) ?
What is the output of print(type([]) is list) ?
I am unsure on how to approach the justification as to why Q1. yields False, yet Q2. yields True. I am following the guidance from a relevant post detailing the nuances of the keyword is, yet I fail to see where the two differ when comparing lists vs sets.
This is not about the nuances of is.
{} in Python is an empty dictionary. There is no literal for creating an empty set in Python (see this answer, and the actual docs). If you were to try type(set()) is set, you would produce True.

From string to fstring [duplicate]

This question already has answers here:
Transform string to f-string
(5 answers)
Closed 2 years ago.
I'm trying to pull a string from JSON, then convert it to an f string to be used dynamically.
Example
Assigned from JSON I get
whose_fault= "{name} started this whole mess"
How to build a lambda to convert it to an f-string and insert the given variable? I just can't quite get my head around it.
I know similar questions have been asked, but no answer seems to quite work for this.
Better question. What's the most pythonic way to insert a variable into a string (which cannot be initially created as an f-string)?
My goal would be a lambda function if possible.
The point being to insert the same variable into whatever string is given where indicated said string.
There is no such thing as f-string type object in python. Its just a feature to allow you execute a code and format a string.
So if you have a variable x= 2020, then you can create another string that contains the variable x in it. Like
y = f"It is now {x+1}". Now y is a string, not a new object type,not a function

What does this syntax mean or do? [duplicate]

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 2 years ago.
I am starting out practicing python and came across this little code on leetcode:
def maxProfit(self, prices: List[int]) -> int:
Could someone please explain what the colon after prices does and what does List[int] and -> do?
I've just used a colon to slice lists/strings and denote the start of a code block indentation.
Reading online I realized that prices : List[int] means that price is the argument name and the expression means that prices should be a list of integers and the return type of the function should be an integer.
Can someone tell me if this is correct or would like to expand on it?
They are type annotations, List[int] refers to prices being a list of ints. While -> gives the type of the returning value, here maxProfit is supposed to return an int.
You are not required to use them.
Those are called annotations or type hints. They basically tell the python interpreter of what type the input parameters should be and what is the function going to return.
So in
def maxProfit(self, prices: List[int]) -> int:
List[int] signifies that the function is expecting a list of integers as the input value of prices. But for it to actually work you have to import List from typing module.
Then -> int signifies that the functions return value is of type integer.
These will not make the code any better, but are helpful for autocomplete and profiling the code. If you are a beginner you don't have to worry about these just now.

Python Passing list by its name to a function [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
names=['abcd','efgh']
nameoflist='names'
def(nameoflist=[]):
return nameoflist
I want to be able to return the entire list from the function
Assuming names is global as specified in the question, you can do this
names=['abcd','efgh']
nameoflist='names'
def return_names(nameoflist):
return globals()[nameoflist]
However, this is pretty ugly, and I'd probably try another way to do it. What do you need the name for? Is there any other way to get the information you're asking for?
This one way to do what you are asking. But it is not good programming.
names=['abcd','efgh']
def list_by_name(list_name):
return eval(list_name)
print(list_by_name('names'))
Also, argument list_name should be a string. It should not default to a list, which would make the function to fail if called without argument. It should not have a default value.

Joining Lists and Splitting Strings [duplicate]

This question already has answers here:
Why is it string.join(list) instead of list.join(string)?
(11 answers)
Closed 7 years ago.
I have some previous experience with C++ and just getting started up with Python. I read this text from Dive into Python :
In my experience, a general idea is, if you want to perform an operation on object 'O', you call a method on that object to do it.
Eg. If I have a list object, and I want to get summation of all elements, I would do something like :
listObject.getSumOfAllElements()
However, the call given in above book excerpt looks a little odd to me. To me this would make more sense :
return (["%s=%s" % (k, v) for k, v in params.items()]).join(";")
i.e. join all the elements of the list as a string, and here, use this parameter ';' as a delimiter.
Is this a design difference or just syntactically a little different than what I am thinking ?
Edit:
For completion, the book says this a little later :
Is this a design difference or just syntactically a little different than what I am thinking?
Yes, I think it is by design. The join function is intentionally generic, so that it can be used with any iterable (including iterator objects and generators). This avoids implementing join for list, tuple, set etc separately.

Categories

Resources