Is there an alternative for sys.exit() in python? - python

try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
I'm not asking about why it is throwing an error. I know that it raises exceptions.SystemExit. I was wondering if there was another way to exit?

os._exit() will do a low level process exit without SystemExit or normal python exit processing.

Some questions like that should really be accompanied by the real intention behind the code. The reason is that some problems should be solved completely differently. In the body of the script, the return can be used to quit the script. From another point of view, you can just remember the situation in a variable and implement the wanted behaviour after the try/except construct. Or your except may test more explicit kind of an exception.
The code below shows one variation with the variable. The variable is assigned a function (the assigned function is not called here). The function is called (via the variable) only after the try/except:
#!python3
import sys
def do_nothing():
print('Doing nothing.')
def my_exit():
print('sys.exit() to be called')
sys.exit()
fn = do_nothing # Notice that it is not called. The function is just
# given another name.
try:
x = "blaabla"
y = "nnlfa"
if x != y:
fn = my_exit # Here a different function is given the name fn.
# You can directly assign fn = sys.exit; the my_exit
# just adds the print to visualize.
else:
print("Error!")
except Exception:
print(Exception)
# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit().
fn()

Related

Should the try/except be placed in the function declaration or call?

Both these snippets do the same thing:
Try/except in function declaration:
def something():
try:
# code goes here
except:
print("Error")
sys.exit(1)
something()
Try/except in function call:
def something():
# code goes here
try:
something()
except:
print("Error")
sys.exit(1)
Is there one that is better/more Pythonic/recommended by PEP8 or is it just up to personal preference? I understand that the second method would get tedious and repetitive if the function needs to be called more than once, but assuming the function is only called once, which one should I use?
the general rule is "only catch exceptions you can handle", see here for an explanation
note that an uncaught exception (in most languages) will cause the program to exit with an unsuccessful status code (i.e. your sys.exit(1)), it will probably also print out a message saying that an exception occurred. your demo therefore is emulating default behaviour, but doing it worse
further, you're catching every exception and this is generally bad style, e.g. you'll implicitly catch SystemExit and other internal exceptions that you probably shouldn't be dealing interacting with

How could I pass block to a function in Python which is like the way to pass block in Ruby

In Ruby, I can pass a block of code to a method.
For example, I can pass different code blocks to get_schedules_with_retries method.
And invoke the block by calling black.call
I'd like to know how could I implement that logic in Python,
Because I have lots of code blocks, need retry pattern.
I don't like copy paste the retry logic in many code blocks
Example:
def get_schedules_with_retries(&block)
max_retry_count = 3
retry_count = 0
while (retry_count < max_retry_count)
begin
schedules = get_more_raw_schedules
block.call(schedules)
rescue Exception => e
print_error(e)
end
if schedules.count > 0
break
else
retry_count+=1
end
end
return schedules
end
get_schedules_with_retries do |schedules|
# do something here
end
get_schedules_with_retries do |schedules|
# do another thing here
end
In Python, a block is a syntactic feature (an indentation under block opening statements like if or def) and not an object. The feature you expect may be a closure (which can access variables outside of the block), which you can achieve using inner functions, but any callable could be used. Because of how lambda works in Python, the inline function definition you've shown with do |arg| is limited to a single expression.
Here's a rough rewrite of your sample code in Python.
def get_schedules_with_retries(callable, max_retry_count = 3):
retry_count = 0
while retry_count < max_retry_count:
schedules = get_more_raw_schedules()
try:
callable(schedules)
except: # Note: could filter types, bind name etc.
traceback.print_exc()
if schedules.count > 0:
break
else:
retry_count+=1
return schedules
get_schedules_with_retries(lambda schedules: single_expression)
def more_complex_function(schedules):
pass # do another thing here
get_schedules_with_retries(more_complex_function)
One variant uses a for loop to make it clear the loop is finite:
def call_with_retries(callable, args=(), tries=3):
for attempt in range(tries):
try:
result=callable(*args)
break
except:
traceback.print_exc()
continue
else: # break never reached, so function always failed
raise # Reraises the exception we printed above
return result
Frequently when passing callables like this, you'll already have the function you want available somewhere and won't need to redefine it. For instance, methods on objects (bound methods) are perfectly valid callables.
You could do it like this:
def codeBlock(paramter1, parameter2):
print("I'm a code block")
def passMeABlock(block, *args):
block(*args)
#pass the block like this
passMeABlock(codeBlock, 1, 2)
You do so by defining a function, either by using the def statement or a lambda expression.
There are other techniques however, that may apply here. If you need to apply common logic to the input or output of a function, write a decorator. If you need to handle exceptions in a block of code, perhaps creating a context manager is applicable.

try/except and descision making

I am working on a function which takes different kinds of date_formats as an argument and dispatches it to a function, which is in charge for parsing this format
In other words:
def parse_format(date_format):
# descision making happens here
try:
from_timestamp(date_format)
except:
pass
try:
from_dateformat(date_format)
except:
pass
def from_timestamp(format):
# raise if not in charge
def from_dateformat(format):
# raise if not in charge
def from_custom_format(format):
# raise if not in charge
Currently, parse_format has multiple try/except blocks. Is this the way to go, or is there a more obvious way to do it? Furthermore, how do I handle the case, where every function call fails?
I would do something like this:
class UnrecognizedFormatError(Exception):
pass
def parse_format(date_format):
methods = (from_timestamp, from_dateformat)
for method in methods:
try:
return method(date_format)
except:
pass
raise UnrecognizedFormatError
But also some key points:
except without a specific exception is bad, because a exception can be thrown from unexpected places, such as running out of memory, or a keyboard interrupt in a script. So please use the except SomeException as e form, and use a specific exception type.
If every function fails, this code will throw a UnrecognizedFormatError, allowing the function's user to respond appropriately.
Well, I would look at this as a great place for try/except/else/finally - the else catching your final case where every function call fails, and the 'finally' being run whatever happens in your try/except statements. If your exceptions are appropriately chosen, then it will pick the right function for you.
Also, I'm guessing that this is a learning exercise, as the activity you're describing would be better done in date.strftime()
def from_timestamp(format):
# raise if not in charge
def from_dateformat(format):
# raise if not in charge
def from_custom_format(format):
# raise if not in charge
def parse_format(date_format):
# decision making happens here
try:
from_timestamp(date_format)
except(FirstException):
from_dateformat(date_format)
except(SecondException):
from_custom_format(date_format)
else:
whatever_you_do_if_it_all_goes_wrong()
finally:
thing_that_happens_regardless_of_what's_called()

How to unit test a function that does not return anything?

Is it possible to find the values of the local variables in a function by mocking?
class A:
def f(self):
a = 5000 * 10
B().someFunction(a)
How do I write a unit test for this function? I have mocked someFunction as I do not want the testing scope to go outside the block. The only way I can test the rest of the function is by checking if the value of variable a is 50000 at the end of the function. How do I do this?
A function that does not return anything, doesn't modify anything and does not raise any error is a function that basically have no reason to be.
If your function is supposed to assert something and raise an error,
give it wrong information and check if it does raise the right error.
If your function takes an object and modifies it, test if the new
state of your object is as expected.
If your function output
something to the console, you can temporarily redirect the
input/output stream and test what is written/read.
If none of the above, just delete your function and forget about it :)
With interaction testing, you could check what value someFunction was called with. What happens inside that function, should be tested in the unit test of that function.
Put the body of the function in a try/except block which does not return anything and return true if successful. This does not break the existing code.
ex:-
def fun():
try:
# function code
return True
except Exception as e:
raise Exception(str(e))

Python functions return 1 when there is an exception

Could you please explain why does the followin function return "1" when there is an exception? What is the purpose of returning "1"?
def initialize():
"""
Starting point for the program.
"""
try:
go = Car()
print "Instance of Car created"
except KeyboardInterrupt:
return 1
It's a fairly common idiom in C to return a non-zero value in case of an error.
My hunch here is that the person who created this function was used to programming in C and unfamiliar with exception handling. It's impossible to tell without a larger code sample, but if I'm right, then there is probably some sort of error handling present where this function is called in the case that this function returns 1, or a non-zero value.
If this is the case, a more proper way to use the exception would be to either use raise to pass the exception upward to be handled else where, or handle the exception right there in the function.
In my opinion there's no need to do this, only if the Car() constructor takes too long and you want to deal with it once initialize() returns.

Categories

Resources