Python return function as results

Best way to return a value from a python script

I wrote a script in python that takes a few files, runs a few tests and counts the number of total_bugs while writing new files with information for each (bugs+more). To take a couple files from current working directory:

When that job is done, I’d like the script to ‘return total_bugs’ but I’m not sure on the best way to implement this. Currently, the script prints stuff like:

[working directory] [files being opened] [completed work for file a + num_of_bugs_for_a] [completed work for file b + num_of_bugs_for_b] . [work complete] 

A bit of help (notes/tips/code examples) could be helpful here. Btw, this needs to work for windows and unix.

It’s generally a bad idea to try to use the return value of an executable to return anything but an error code or 0 for success. What are you going to do with this value when it’s returned?

Читайте также:  Не загружается index php

Don’t know about windows, but in linux it is common for programs to output the result to stdout. It seems like normally your script prints a bunch of information, but perhaps with a different flag (maybe c for count?), it just prints the total count of files, e.g. myscript.py -c -i input_name1 input_name2

@ Wooble, it is a script for finding bugs in report files. The value allows to estimate how well the report files are written.

@arghbleargh, I decided to go with an extra bug report file but, pending on what my supervisor decides, I might change it to something like your suggestion. Thanks.

1 Answer 1

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you’d have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import . def main(): # calculate stuff return [1,2,3] 

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys # calculate and stuff sys.exit(100) 

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

( os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you’d have to use stdout to communicate with the outside world (like you’ve described). But that’s generally a bad idea unless it’s a parser executing your script and can catch whatever it is you’re reporting to.

import sys # calculate stuff sys.stdout.write('Bugs: 5|Other: 10\n') sys.stdout.flush() sys.exit(0) 

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There’s also the option to simply write information to a file, and store the result there.

# calculate with open('finish.txt', 'wb') as fh: fh.write(str(5)+'\n') 

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it’s a good option to communicate between processes. Especially if they should run multiple tasks and return values.

Источник

How does return() in Python work?

In order to get a value from a function in any programming language, we use the return() statement. Likewise, in Python, the return() statement is used to exit a function and returns a value from a function. In this tutorial, we will read about various ways to use the return() statements in Python.

Table of contents

  1. Introduction to return() statement
  2. Returning Multiple Values in Python
  3. Argument in return() function
  4. Function returning another function
  5. Closing thoughts

return() in Python

The return() statement, like in other programming languages ends the function call and returns the result to the caller. It is a key component in any function or method in a code which includes the return keyword and the value that is to be returned after that.
Some points to remember while using return():

  • The statements after the return() statement are not executed.
  • return() statement can not be used outside the function.
  • If the return() statement is without any expression, then the NONE value is returned.

Syntax of return() in Python:

 def func_name(): statements. return [expression] 

Using a return() statement for returning multiple values in Python

Python also gives an option to return multiple values from a function and in order to do that the user just needs to add multiple return values separated by commas. Also known as a tuple, can be created with or without using the ().

Input:

 def statFun(a, b): difference = a-b percent_diff = (difference/a)*100 return difference, percent_diff; difference, percent_diff = statFun() print (difference) print (percent_diff) 

Here, the function statFun() gives to values and by using tuple we return both of the values.

Output:

return() in Python with an argument

In Python, arguments can be used with a return statement. To begin with, arguments are the parameter given by the user and as we know, the argument is the value(s) as input, which is given by the user to the function.

Input:

 def divNum(a, b): if b != 0 return a/b; else: return 0; print (divNum(4, 2)) print (divNum(2, 0)) 

Here, the function divNum() accepts two arguments and if the second argument is non zero it divides them otherwise returns 0.

Output:

Function returning another function in Python

As we know functions are treated as first-class objects in Python, therefore we can return a function from another function. A first-class object is an object that can be assigned to a variable, passed as an argument to a function, or used as a return value in a function.
A function that takes a function as an argument, returns a function as a result, or both is known as a higher-order function.

Input:

 def func_1(a): def func_2(b): return a-b return func_2 x = func_1(100) print ("The value of a-b is", x(50)) def another_func(a): return a*10 def func(): return another_func y = func() print ("\nThe value of a*b is" y(10)) 

Output:

 The value of a-b is 50 The value of a*b is 100 

Closing thoughts

The return statement sends any object from the function back to the caller code. Since the return statement is a key part of any function or method, if you learn how to use it correctly, you can move to complex codes. One can learn about more Python concepts here.

Источник

Python return statement

Python return statement

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

The python return statement is used to return values from the function. We can use the return statement in a function only. It can’t be used outside of a Python function.

Python Function without return statement

Every function in Python returns something. If the function doesn’t have any return statement, then it returns None .

def print_something(s): print('Printing::', s) output = print_something('Hi') print(f'A function without return statement returns ') 

Python Function Without Return Statement

Output:

Python Return Statement Example

We can perform some operation in a function and return the result to the caller using the return statement.

def add(x, y): result = x + y return result output = add(5, 4) print(f'Output of add(5, 4) function is ') 

Python Return Example

Output:

Python return statement with expression

We can have expressions also in the return statement. In that case, the expression is evaluated and the result is returned.

def add(x, y): return x + y output = add(5, 4) print(f'Output of add(5, 4) function is ') 

Python Return Statement With Expression

Output:

Python return boolean

Let’s look at an example where we will return the boolean value of the argument of a function. We will use bool() function to get the boolean value of the object.

def bool_value(x): return bool(x) print(f'Boolean value returned by bool_value(False) is ') print(f'Boolean value returned by bool_value(True) is ') print(f'Boolean value returned by bool_value("Python") is ') 

Python Return Boolean

Output:

Python return string

Let’s look at an example where our function will return the string representation of the argument. We can use the str() function to get the string representation of an object.

def str_value(s): return str(s) print(f'String value returned by str_value(False) is ') print(f'String value returned by str_value(True) is ') print(f'String value returned by str_value(10) is ') 

Python Return String

Output:

Python return tuple

Sometimes we want to convert a number of variables into a tuple. Let’s see how to write a function to return a tuple from a variable number of arguments.

def create_tuple(*args): my_list = [] for arg in args: my_list.append(arg * 10) return tuple(my_list) t = create_tuple(1, 2, 3) print(f'Tuple returned by create_tuple(1,2,3) is ') 

Python Function Return Tuple

Output: Further Reading: Python *args and **kwargs

Python function returning another function

We can return a function also from the return statement. This is similar to Currying, which is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.

def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is ') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is ') 

Python Return Function

Output:

Python function returning outer function

def outer(x): return x * 10 def my_func(): return outer output_function = my_func() print(type(output_function)) output = output_function(5) print(f'Output is ') 

Python Function Return Outer Function

Output:

Python return multiple values

If you want to return multiple values from a function, you can return tuple, list, or dictionary object as per your requirement. However, if you have to return a huge number of values then using sequence is too much resource hogging operation. We can use yield, in this case, to return multiple values one by one.

def multiply_by_five(*args): for arg in args: yield arg * 5 a = multiply_by_five(4, 5, 6, 8) print(a) # showing the values for i in a: print(i) 

Python Return vs Yield

Output:

Summary

The python return statement is used to return the output from a function. We learned that we can also return a function from another function. Also, expressions are evaluated and then the result is returned from the function. You can checkout complete python script and more Python examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью