Importing modules and taking an output - python

I have a previously created a module of the form:
def function1():
....
return ....
def function2():
....
return ....
def function3():
....
return ....
if __name__ == "__main__":
do something
Now in another file I am importing this using:
from file1 import function3
def function4(a, b):
for n in range(b):
t = function3()[1] # getting the second output from the third function
if ...:
....
else:
....
return ....
print(function4(a,b)) # with some input a and b
Now when I run the function in the second file from the command prompt why does this produce the flashing underscore as if there is an infinite loop?
If b = 1, it produces one output as expected, but why does it not work for b > 1?
(Note: function3()[1] will produce a different output each time.)
There is a lack of detail in the functions as this is related to a coursework assignment but having difficulties importing.

Related

Late code evaluation and also printing the code

I want to pass code to a test() routine, which has to :
print the code
execute it
and finally do stuff with the result.
should handle args in the background
For quick code snippets I can use eval(code-string), like this:
def test_eval(expr_str, expected):
global a,b
res = eval(expr_str) == expected
print(f'{res} : {expr_str}')
but for:
code with assignment
test() should do argumentless calling of fun(), even for fun(a, b...)
or longer code
the approach is unusable.
SOLVED
def test(fun,expected,args):
res = fun(*args) == expected
expr = inspect.getsource(fun)
print(f'{res} : {expr}')
def tests():fun()
def w(a,b):#args
a += b #assignment
return a.sym == "(a + b)"
a = ...
b = ...
test(w,True,(a,b))
better ideas?

Declaring a var usable by another function using a import in a secondary script

Is there a way to make a function_a define a variable usable inside another function_b so that both are possible to import in a project ? Something like so:
Script_1
def func_a(str):
if str == 'Yes'
nb = 1
else:
nb=0
return nb
def func_b(int)
calc = (nb+int)**2
return calc
Script_2
from Script_1 import func_a, func_b
func_a('Yes')
func_b(5)
My attempt at declaring nb in Script_2 did not work as python tried to find it in Script_1. I hope this can give an idea of what I am trying to do. Also, the names of the variable are but a representation of type (strand int) I am looking for. Python is rather new to me and I am still learning. Thanks in advance.
The standard way to pass state from one function to another is for one function to return the value and for the other to take it as an argument.
# Script_1
def func_a(msg: str) -> int:
if msg == 'Yes':
return 1
else:
return 0
def func_b(na: int, nb: int) -> int:
return (na + nb)**2
# Script_2
# from Script_1 import func_a, func_b
nb = func_a('Yes')
print(func_b(5, nb))
By adding nb as an argument to func_b, we can take the return value from func_a and pass it to func_b. (Doing weird stuff with injecting data into the global namespace is technically possible, but it makes your code extraordinarily difficult to debug.)
Thanks to Amadan's suggestion, I was able to do this:
class test(object):
def __init__(self,string):
self.string = string
if string == 'Yes':
self.factor = 1
else:
self.factor = 0
def func(self, num):
calc = (num+self.factor)**2
return calc
And can be used as such in another file once saved in test.py:
from test import test
test('Yes').func(3)
test('No').func(3)

How can I increase code readability in python for this?

I am running my script in Flask and to catch and print the errors on the server I have made functions that either return None if succeeded else return an error message.
The problem is I have many functions which runs one after another and uses global variable from earlier function, this makes the code unorganized. What can I do?
App.py
from flask import Flask
from main import *
app = Flask(__name__)
#app.route('/')
def main():
input = request.args.get('input')
first_response = function1(input)
if first_response is None:
second_response = function2() # no input from hereon
if second_response is None:
third_response = function3() # functions are imported from main.py
if third_response is None:
...
if ...
else ...
else:
return third_response
else:
return second_response
else:
return first_response
main.py
def function1(input):
global new_variable1
if input is valid:
new_variable1 = round(input,2)
else:
return "the value is not integer"
def function2():
global new_variable2
if new_variable1 > 8:
new_variable2 = new_variable1 / 8
else:
return "the division is not working, value is 0"
def function3():
...
This is just a demo of what's going on. The last function will return a value either side. So if everything goes right I would be able to see the right output as well as I will see error on any given function.
The code works fine, but I need better alternative to do this.
Thanks!
Ah...you have (correctly) determined that you have two things to do:
Process your data, and
Deal with errors.
So let's process the data replacing global with parameteters (and come back to the error handling in a bit). You want to do something like this.
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
def function2(a_rounded_number):
if a_rounded_number > 8:
return a_rounded_number / 8
So each function should return the results of its work. Then the calling routine can just send the results of each function to the next function, like this:
app.py
# [code snipped]
result1 = function1(the_input_value)
result2 = function2(result1)
result3 = function3(result2)
But...how do we deal with unexpected or error conditions? We use exceptions, like this:
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
else:
raise ValueError("some_number was not valid")
and then in the calling routine
app.py
try:
result1 = function1(some_input_value)
except (ValueError as some_exception):
return str(some_exception)

how to pass variables between complex python class and function?

one input
one output
I want to get output through one long process.Because the process is so long, I have to continue input and return output. Is there some convenient way to get output inside the class or function without pass one function and other?
the demo function as follows:
main.py
from run import class1
def f1(input):
c=class1()
output=c.cf2(input)
return output
run.py
class1(input):
def cf1(input):
ca=class2()
output=ca.c2f1(input)
return output
def cf2(input):
output=self.cf1(input)
return output
class2():
def c2f1(user_input):
variable=user_input
output=self.c2f2(variable)
return output
def c2f2():
y=…
return y

Get inner function result without interaction of outer function in python

I want to get inner function result so i code it like
def main():
def sub():
a = 1
print a
exec main.__code__.co_consts[1]
using above code working successfully but i want to pass the argument to the sub function like...
def main():
def sub(x):
a = x + 1
return a
ans = exec main.__code__.co_consts[1]
print ans
in that problem is i don't know how to pass that x value.
that work must need to exec so that how to pass that x value with exec without interaction of main function
Maybe something like the code below, as suggested by this SO answer
def main():
def sub():
a = x + 1
print a
return a
exec(main.__code__.co_consts[1], {'x': 1} )

Categories