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
Related
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)
Problem statement : I want to pass value returned by one function to another function from my test file.
test_abc.py
#pytest.fixture(scope='function')
def hold_value():
def _value(resp):
return resp
return _value
#when(parsers.cfparse('user did something with value "{a}" and "{b}" and “{c}"'))
def func1(hold_value, a, b, c):
response = do_something(a,b,c)
hold_value(response)
#then('user validate if above step is correct')
def func2(hold_value):
call_another_func_and_pass_above_response(hold_value)=> what can I do here to get value from fixture
This is test file where I tried creating fixture to hold value returned by one function and then use it in other functions
I am not sure, if it is right way of doing this, I want to pass values from one test step to another.
Can anyone please guide me to achieve desired result
I am able to achieve solution by using context as a fixture
#pytest.fixture(scope='function')
def context():
return {}
#when(parsers.cfparse('user did something with value "{a}" and "{b}" and “{c}"'))
def func1(context, a, b, c):
response = do_something(a,b,c)
context[‘response’] = response
#then('user validate if above step is correct')
def func2(context):
call_another_func_and_pass_above_response(context.get(‘response’))
I have this file with unit tests:
#file tests.py
class TestResults(TestBase): ...
class TestRegisteredFunctions(TestBase):
"""Tests functions registered dynamically."""
def testNewFunction(self):
"""Server must register new functions."""
# Register new function
def square(num):
return num * num
self.server.register('square', square)
res = self.jsonrpc_req(1, 'square', [2])
self.assertEqual(res['result'], 4)
Most of the code is omitted because will not be relevant.
My problem is I need to grab that "square" function.
For example doing getattr(tests, 'square') in another module would correctly get me that square function. How can I achieve such result?
Like ruby, how to pass code block and get it executed (yield) where you pass it. I am trying to achieve same thing in python 3.5
This is what my pseudo code looks like. How to achieve what I am trying to do. What changes would I have to make?
# Calculate all
# I want this function should yield whatever method passed to it
# THIS MUST BE A CLASS
class Calculator:
def __init__(self):
self.prefix = "hello"
def calculate(self, function_name)
local_val = 10
print("executing {} function with {}".format(function_name, self.prefix))
result = function_name(local_val)
print(result)
return result
# I want to pass these functions to Calculator().calculate() method
def add_one(x):
return x+1
def minus_one(x):
return x-1
def divide_in_half(x):
return x/2
Calculator().calculate(add_one(?))
# expect this to print:
# executing add_one function with hello
# 11
Calculator().calculate(minus_one(?))
# expect this to print:
# executing minus_one function with hello
# 9
Calculator().calculate(divide_in_half(?))
# expect this to print:
# executing divide_in_half function with hello
# 5
Functions are objects in Python, so you can just do this:
Calculator().calculate(add_one)
Calculator().calculate(minus_one)
Calculator().calculate(divide_in_half)
Note that this passes the function itself and not the name of the function. (In your code, you would have to access function_name.func_name to obtain the function's name, so I would suggest renaming function_name to fn, which is short for "function.")
You don't even need to declare predefined functions. You can use the lambda syntax to pass an anonymous callable on the fly:
# Instead of add_one, for example:
Calculator().calculate(lambda x: x + 1)
Initially, fix your __init__ so it doesn't complain when called with no args:
def __init__(self, prefix="hello")
use the function __name__ in the call to format done in calculate:
msg = "executing {} function with {}"
print(msg.format(function_name.__name__, self.prefix))
then pass the function objects along:
Calculator().calculate(add_one)
# expect this to print:
# executing add_one function with hello
# 11
Calculator().calculate(minus_one)
# expect this to print:
# executing minus_one function with hello
# 9
Calculator().calculate(divide_in_half)
# expect this to print:
# executing divide_in_half function with hello
# 5
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.