Reputation: 855
I've got a code with different functions. Inside one of them there is a condition. I have to check if this condition occur to execute another function.
What's the proper way to do that? I've tried something like this but it doesn't work
Example:
class MyClass:
def thisFunction(self):
try:
"I'm doing things"
except:
self.stop = print("That's already done!")
def thisOtherFunction(self):
"I'm doing things with things done in thisFunction"
s = MyClass()
s.thisFunction()
if self.stop == None:
s.thisOtherFunction()
else:
pass
Thanks a lot!
Update
Actually it's a lot simplier doing:
class MyClass:
def thisFunction(self):
try:
"I'm doing things"
except:
self.stop = print("That's already done!")
def thisOtherFunction(self):
try:
"I'm doing things with things done in thisFunction"
except:
pass
s = myClass()
s.thisFunction()
s.thisOtherFunction()
Thanks to Adam Smiths's example, I simply didn't think about that. Maybe it's not so much elegant, though.
Update2
Another way is to use def __init__
in this way:
class MyClass:
def __init__(self):
self.commandStop = False
def thisFunction(self):
try:
"I'm doing things"
except:
self.commandStop = True
def thisOtherFunction(self):
"I'm doing things with things done in thisFunction"
def conditionToGo(self):
if self.commandStop == False:
print("That's already done!")
else:
s.thisOtherFunction()
s = myClass()
s.thisFunction()
s.conditionToGo()
Upvotes: 0
Views: 48
Reputation: 54173
I've made patterns before where I had to do a series of transforms to a value and it needs to pass a test each time. You could construct that with:
def pipeline(predicate, transformers):
def wrapped(value):
for transformer in transformers:
value = transformer(value)
if not predicate(value):
raise ValueError(f"{value} no longer satisfies the specified predicate.")
return value
return wrapped
Then, to construct an example, let's say I need to do some math on a number but ensure that the number never goes negative.
operations = [
lambda x: x+3,
lambda x: x-10,
lambda x: x+1000,
lambda x: x//2
]
job = pipeline(lambda x: x>0, operations)
job(3) # fails because the sequence goes 3 -> 6 -> (-4) -> ...
job(8) # is 500 because 8 -> 11 -> 1 -> 1001 -> 500
Upvotes: 1