What's the param (`_`) in a function? [duplicate] - python

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 3 years ago.
I saw a function like bellow, I don't know the _ meaning.
def child_handler(signum, _):
logging.warn('received SIGQUIT, doing graceful shutting down..')
what's the _ there?
but, however, if we ignore the _, why we need there an ignored param?

the _ variable is just a way to say that it's not going to be used further down the line.
Basically, you don't care what the name is because it'll never be referenced.

It essentially is a way of ignoring the value of the variable, and we don't want to use it down the line.
Another way of thinking is that it is a placeholder for the value that will be ignored
def func(a, b):
return a,b
#I care about both return values
c,d = func(2,3)
#I don't care about the second returned value, so I put a _ to ignore it
c, _ = func(2, 3)
Another good use case of this is when you are running a for loop, but don't care about the index.
for _ in range(10):
#do stuff
Even for functions, it acts like a don't care variable
def func(a, _):
print(a)
func(1, 5)
The output will be 1

The underscore _ in Python can be used for different cases. In this case it means that the second argument of the child_handler function is ignored (so-called "Don't care").

Related

What is the use of '#f' in python? [duplicate]

This question already has answers here:
What does the "at" (#) symbol do in Python?
(14 answers)
How do I make function decorators and chain them together?
(20 answers)
Closed 26 days ago.
#the code given is:
def f(a):
print('hello')
#f
def f(a,b):
return a%b
f(4,0)
What I expected to happen was a zero division error, instead it printed hello.
When I write the same code without '#f'
it gives the expected result as output
I've never seen symbol/expression being used in python
This is new and Google too has nothing about it
Decorator syntax is a shorthand for a particular function application.
#f
def f(a, b):
return a%b
is roughly equivalent to
def tmp(a, b):
return a % b
tmp2 = f(tmp)
f = tmp2
(Reusing the name f for everything makes this tricker to understand.)
First, your division-by-zero function is defined. Next, your original function f is called: it prints hello and returns None. Finally, you attempt to call None with two arguments, but it isn't callable, resulting in the TypeError you allude to.
In short, the decorator syntax takes care of treating all the things that would otherwise have been named f as distinct objects and applying things in the correct order.

How to pass a specific value from Tuple into a function [duplicate]

This question already has answers here:
Getting one value from a tuple
(3 answers)
Closed 2 years ago.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(a_tuple(variable1))
Is there a way I can pass a specific value from a tuple into a function? This is a terrible example, but all I need to know is if I can pass variable1 from the tuple into the function, I understand in this instance I could just pass in variable 1, but its for more complicated functions that will get its data from a tuple, and I don't like the look of that many variables, too messy.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(*a_tuple)
This code would obviously provide an error as it unpacks the tuple and inserts 2 variables, to make this work in my program I would need a way to pass either variable1 or variable2 into the function. My question is can I define exactly which items from a tuple are passed into the function when calling the function? Latest version of Python if it matters.
P.S. I wrote print("hello world") for the first time 7 days ago, this is my first language and my first question I couldn't find an answer to. Go easy on me, and thank you for your time.
In the code you provided you don't have a tuple you have a list. But it is still pretty much the same.
In your example lets say that you wanted to pass the first variable you would do it like this:
my_function(a_tuple[0])
If you don't understand why there is a zero here and how does this work I highly suggest learning about lists before functions.
You just need to access individual elements of the tuple, using index notation:
my_function(a_tuple[0])
or
my_function(a_tuple[1])
You could, if you wanted, write a new function which takes a tuple and an index, and calls my_function with the appropriate element:
def my_other_function(tuple, index):
return my_function(tuple[index])
But I don't see how there would be much gain in doing that.
you can index a tuple or use the index method.
def my_function(a):
pass
my_function(a_tuple[0])
if you want to get the index of a value use the index() method
a_tuple.index(variable1) #this will return 0

Having difficulty understanding how function works [duplicate]

This question already has answers here:
Return multiple values over time
(2 answers)
Closed 5 years ago.
I've written a function in python to see If i know what I'm doing but unfortunately I'm not. I thought my defined arg variable will hold a number and multiply each of the numbers which *args variable holds and print it all at a time. But, it is giving me the first result only.
This is what I've written:
def res_info(arg,*args):
for var in args:
return var*arg
print(res_info(2,70,60,50))
Having:
140
Expected:
140
120
100
I don't understand why I'm not getting all the results. Thanks for taking a look into it.
You are on the right path. The problem you had was due to your use of the return statement. Use yield instead.
>>> def res_info(arg,*args):
for var in args:
yield var*arg
>>> list(res_info(2,70,60,50))
=> [140, 120, 100]
So, what was happening was, even though your logic was correct, since there was a return statement in the loop, your loop hence was never fully executed and your program scope would come out on the first iteration of the loop itself (ie, when var = 70).
Using yield, solved the problem as it returns a Generator object after all calculations, and hence does not exit the loop like return does.
def res_info(arg,*args):
result = []
for var in args:
result.append(var*arg)
return result
print(res_info(2,70,60,50))

Python _ meaning when assigned after for loop [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 5 years ago.
I am not an experienced Python programmer and I saw following code which I couldn't understand. Unfortunately syntax is very tricky and difficult to search for on the internet. Though I did find some explanation to '_' and '__' but I am not sure if following code has any special meaning for '_'
if not allowed_positions:
return (0, 0)
_, point = max([(self.point(graph.find_point(p), self), p) for p in allowed_positions])
In the above code I don't understand why there is an underscore with comma '-,' before point = ....
_ is just used as a placeholder for a discarded variable.
Let's assume there is a function which returns a tuple with two elements, and I am interested only in the second part of the tuple, then it is a general practice to use _ for the variable I do not need.
e.g.
>>> def return_tuple():
... return (24,7)
...
>>> _, days = return_tuple()
>>> days
7
_ is a placeholder for variables that you don't need to store data in.
You can use it for tuple unpacking and it's common to practice to use an underscore to denote that that value will not be used later in the script.
If you had something like this: soldiers = [('Steve', 'Miller'), ('Stacy', 'Markov'), ('Sonya', 'Matthews'), ('Sally', 'Mako')]
and, you wanted to get only the last names you would do this:
for _, last_name in soldiers:
# print the second element
print(last_name)
Instead of doing:
for first_name, last_name in soldiers:
print(last_name
Since you don't need to use first_name. You replace it with _ so you don't store unnecessary variables

Python calling function by string name from code [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Here is what I would like to be able to do:
I have a file called functions, with lots of functions. The functions are all essentially the same, functionally speaking (i.e., they are all of the form: pandas.Dataframe -> pandas.Dataframe). Obviously, they do different things to the Dataframe, so in that sense they are different.
I'd like to be able to pass my main function a list of strings, which would be the actual function names in the module, and have my program translate the strings into function calls.
So, basically, instead of:
functions = [module.functionA, module.functionB, module.functionC]
x = g(functions)
print(x)
> 'magical happiness'
I would have:
function_strings = ['functionA','functionB','functionC']
functions = interpret_strings_as_function_calls(module,function_strings)
x = g(functions)
print(x)
> 'magical happiness'
Is there a way to do this? Or do I need to write a function in the module that matches each string with it's corresponding function? i.e.:
def interpret_strings(function_string):
if function_string == 'functionA':
return module.functionA
elif function_string == 'functionB':
return module.functionB
etc.
(or in a switch statement, or whatever)
You can use getattr(module, function_string).

Categories