I have a python function
def foo():
'''
some code
'''
return handle.fetch_some_result()
and I want to achieve the goal:
def foo():
'''
some code
'''
value = handle.fetch_some_result()
print value
return value
So how can I achieve this but not use the above code(a little ugly). Are there some elegant ways to do that but not use the middle var(value) or is it possible in python?
Thx!
You can write easily a helper function that does that, I don't know any built-in:
def print_return(value):
print value
return value
Nothing wrong with how your doing it. If you don't like the print in the function, you could alwsy print the return value.
def foo():
'''
some code
'''
return handle.fetch_some_result()
result = foo()
print result
Related
How can I send a value which in a process to another process? For example I have something like this code piece. I want to print value in xFunc. Can someone explain how can I do it? Thank you.
def yFunc():
value = 5
def xFunc():
print(value)
def smap(f):
return f()
def main():
f_x = functools.partial(xFunc)
f_y = functools.partial(yFunc)
with Pool() as pool:
res = pool.map(smap, [f_x, f_y])
if __name__ == '__main__':
main()
Edit: value is not constant number it is changing continuously.
Edit2: I found a way for my problem. Here the solution:
https://stackoverflow.com/a/58208695/16660763
There are several ways.
One way would be to use the global keyword. like this:
def yFunc():
global value
value = 5
def xFunc():
print(value + 1)
yFunc()
xFunc()
Or like this:
value = 5
def yFunc():
global value
value = value + 1
def xFunc():
print(value)
yFunc()
xFunc()
Another way would be to pass the variable to the function like this:
def yFunc():
value = 5
return value
def xFunc(x):
print(x)
xFunc(yFunc())
Hope that's what you were asking.
Python has provided some tools to realize it.
Considering Pipes, Queues, Value and Managers.
Sorry for the title, I hope it reflects correctly my problem :
In the following code, I was expecting the result to be result 0 1 2 but instead I have 2 2 2. The code inside my_function seems to be interpreted with the last instance of obj. What is wrong ?
class Example:
def __init__(self, x):
self.x = x
def get(self):
return self.x
a_list = []
for index in range(3):
obj = Example(index)
def my_function(x):
#some stuff with x like obj.another_function(x)
return obj.get()
a_list.append(my_function)
for c in a_list:
print(c())
When you define this
def my_function():
return obj.get()
Python will understand that my_function should run the get() method of an object called obj and return the value. It won't know the value of obj and what the get() method does until you attempt to call it.
So, you are actually defining three different functions that will eventually do the same thing. And, in the end, running the same code thrice.
But why is the return 2 2 2?
Because after the last iteration, the value of obj is Example(2)* because you redefine its value at every iteration, and the last one remains.
*
because of this line obj = Example(index)
Understanding a few things about how python works will help you understand what's happening here. Here obj is a closure, closures are evaluated at call time, not when the function is defined so if I do this:
x = "hello"
def printX():
print x
x = "goodbye"
printX() # goodbye
I get "goodbye" because printX is referencing a global variable in my module, which changes after I create printX.
What you want to do is create a function with a closure that references a specific object. The functional way to do this is to create a function that returns another function:
x = "hello"
def makePrintX(a):
def printX():
# We print a, the object passed to `makePrintX`
print a
return printX
# x is evaluated here when it is still "hello"
myPrintX = makePrintX(x)
x = "goodbye"
myPrintX() # "hello"
If you're having trouble understanding the above example I would recommend reading up on python's scoping rules. For your example, you could do something like this:
class Example:
def __init__(self, x):
self.x = x
def get(self):
return self.x
def makeObjFunction(obj):
def objFunction(x):
return obj.get()
return objFunction
a_list = []
for index in range(3):
obj = Example(index)
my_function = makeObjFunction(obj)
a_list.append(my_function)
for c in a_list:
print(c("some value"))
You are appending three my_functions to the a_list which are all closures over the same Example object. Try:
def my_function():
return obj
<__main__.Example object at 0x0054EDF0>
<__main__.Example object at 0x0054EDF0>
<__main__.Example object at 0x0054EDF0>
You can see they have the same id so calling get() on each should give the same answer.
If you just append the obj.get function (and drop the my_function) it'll work fine.
a_list.append(obj.get)
....
0
1
2
Edit: You've updated your question so to let you do more stuff in my_function(). It's still basically a scoping problem.
def my_func_factory(p_obj):
def my_function(x):
#some stuff with x like obj.another_function(x)
return p_obj.get()
return my_function
for index in range(3):
obj = Example(index)
a_list.append(my_func_factory(obj))
Since my_function can't see obj being reassigned, each instance doesn't pick up the change.
I think append() during the for just append the function address in a_list[]. After for iteration, the a_list is really given the number. Then it discovers the address of my_function, and they get the number in my_function, this is, 2. That's why you get [2,2,2].
Or maybe, in my_function, function give the method of "obj". But for iteration change the "obj" memory address each time, so the symbol "obj" always aim to the newest object Example. Due to my_function always get "obj", you get the same number from the last object.
I'm trying to create function that get a number and return function. For example:
>>> const_function(2)(2)
2
>>> const_function(4)(2)
4
How can I return function as output? I've tried to write this:
def const_function(c):
def helper(x):
return c
return helper(x)
Why is this not working?
You're returning the result of calling the function. If you want to return the function itself, simply refer to it without calling it:
def const_function(c):
def helper(x):
return c
return helper # don't call it
Now you can use it with the desired results:
>>> const_function(2)
<function const_function.<locals>.helper at 0x0000000002B38D90>
>>> const_function(2)(2)
2
>>> const_function(4)(2)
4
Try:
return helper
When you do:
return helper(x)
it calculates the result of helper(x) and returns it. When you return helper it will return the function itself.
I'm trying to write a function right now, and its purpose is to go through an object's __dict__ and add an item to a dictionary if the item is not a function.
Here is my code:
def dict_into_list(self):
result = {}
for each_key,each_item in self.__dict__.items():
if inspect.isfunction(each_key):
continue
else:
result[each_key] = each_item
return result
If I'm not mistaken, inspect.isfunction is supposed to recognize lambdas as functions as well, correct? However, if I write
c = some_object(3)
c.whatever = lambda x : x*3
then my function still includes the lambda. Can somebody explain why this is?
For example, if I have a class like this:
class WhateverObject:
def __init__(self,value):
self._value = value
def blahblah(self):
print('hello')
a = WhateverObject(5)
So if I say print(a.__dict__), it should give back {_value:5}
You are actually checking if each_key is a function, which most likely is not. You actually have to check the value, like this
if inspect.isfunction(each_item):
You can confirm this, by including a print, like this
def dict_into_list(self):
result = {}
for each_key, each_item in self.__dict__.items():
print(type(each_key), type(each_item))
if inspect.isfunction(each_item) == False:
result[each_key] = each_item
return result
Also, you can write your code with dictionary comprehension, like this
def dict_into_list(self):
return {key: value for key, value in self.__dict__.items()
if not inspect.isfunction(value)}
I can think of an easy way to find the variables of an object through the dir and callable methods of python instead of inspect module.
{var:self.var for var in dir(self) if not callable(getattr(self, var))}
Please note that this indeed assumes that you have not overrided __getattr__ method of the class to do something other than getting the attributes.
What is correct way to use data from functions in Python scripts?
Using print, like:
var1 = 'This is var1'
def func1():
print(var1)
func1()
Or - with return:
var1 = 'This is var1'
def func1():
return var1
print(func1())
Both give same result:
$ ./func_var_print_return.py
This is var1
You should return a value when the purpose of the function is to produce a value. This is so functions can use other functions. For example
def add(x,y):
return x + y
def multiply(a,b):
product = 0
for i in range(b):
product = add(product, a) # Note I am calling the add function
return product
Testing
>>> multiply(5,4)
20
Note that I used the return value from add within my multiply function. If I only printed the value from add, I would have been unable to do that.
It depends on the situation. In general I would return it so you can print if you want but if you code changes at some point you can perform other operations with the value
You should always try to return the value.
Think of unit tests -> How would you verify the value if it's not returned?
And as mentioned by "meto" before, if your code changes you can still perform other operations with the value.