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

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.

Related

Can you directly alter the value of a non-list argument passed to a function? [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 13 days ago.
This snippet of python code
def changeValue(x):
x = 2*x
a = [1]
changeValue(a[0])
print(a[0])
Will print the result "1" when I would like it to print the result "2". Can this be done by only altering the function and no other part of the code? I know there are solutions like
def changeValue(x):
x[0] = 2*x[0]
a = [1]
changeValue(a)
or
def changeValue(x):
return 2*x
a = [1]
a[0] = changeValue(a[0])
I am wondering if the argument passed as-is can be treated as a pointer in some sense.
[edit] - Just found a relevant question here so this is likely a duplicate that can be closed.
No it's not possible. If you pass a[0], it's an int and it can't be mutated in any way.
If the int was directly in the global namespace, you could use global keyword. But it's not. So again no.

how do you use return() in python [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 8 months ago.
Can somebody please teach me how to do return? I am doing a course and I just don't understand what return is for and how to use it :(
return is used when defining function so it returns the result of this function.
example:
def test():
return(1)
it returns 1
def test2(a,b):
return(a+b)
it returns the sum of the two values
A return statement is used to end the execution of the function call and “returns” the result.
The statements after the return statement are not executed
For example:
def cube(x):
r = x**3
return r
Maybe this could help you as well:
Print and Return, What's the difference

Iterating through a tuple using a function and *args [duplicate]

This question already has answers here:
Python for loop returns True after first item
(4 answers)
Closed 3 years ago.
I'm trying to make a function using *args. It should take in certain numbers and then output the products of the numbers multiplied by 10.
I'm learning to use *args but I'm having trouble getting the output. My result only outputs the first number in the function. I've tried using a for loop, thinking it would iterate over each character, but it didn't work.
def myfunc(*args):
for args1 in args:
return args1*10
When I run the function:
myfunc(10.1,20)
The expected output should be
(101.0,200.0)
The actual output is
(101.0)
Any help would be appreciated. Thanks.
If I understand you, that's what you need:
def myfunc(*args):
return tuple(map(lambda x: x*10, args))
*args can be retrieved in the function as a list called args. What you do here is just multiplying the first element by 10 and return it, so the function stops.
You should use yield instead of return, to make your function return a generator, which can then be converted to tuple whenever you need
>>> def myfunc(*args):
... for args1 in args:
... yield args1*10
...
>>>
>>> myfunc(10.1,20)
<generator object myfunc at 0x7f20d1ae8ad0>
>>>
>>> tuple(myfunc(10.1,20))
(101.0, 200)

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).

Mutable default arguments in Python [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have written the following python program:
#!/usr/bin/env python
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
print bug()
print bug()
The result i would expect is
[1]
[1]
But i got
[1]
[1, 1]
Is this a bug?
No, this is not a bug and this behaviour has been around in Python for a very long time.
The problem is that the list object is mutable, i.e. you can change it, and when you call a function you don't get a new default value. What's happening is this:
def bug( numbers = [] ):
numbers.append( 1 )
return numbers
At this point the function bug has been created and the list that is default value for numbers created.
print bug()
Now we've called bug once and added 1 to the list that was created when the function was defined.
print bug()
When we call the function again we get the same list as before so we get two 1s added to the list.
The usual solution is to define your function as follows:
def bug(numbers = None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers
Read this for more details.
numbers=[] is evaluated only once (when the function is defined). So it's always the same list.
To avoid this, change the function like this:
def not_a_bug(numbers=None):
if numbers is None:
numbers = []
numbers.append(1)
return numbers

Categories