I have the following code:
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
I was wondering if it came already in any built-in library?
/YGA
Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.
No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:
if causes_exception(func):
# do something
else:
# do something else
But instead, you could just do
try:
func()
except SomeException:
# do something else
else:
# do something
There's assertRaises(exception, callable) in unittest module and this is probably the only place where such check makes sense.
In regular code you can never be 100% sure that causes_exception you suggested are not causing any side effects.
I'm not aware of that function, or anything similar, in the Python standard library.
It's rather misleading - if I saw it used, I might think it told you without calling the function whether the function could raise an exception.
Related
Anyone can tell me about only try function is possible in exception handling in python
because i want to use only try function not exception method
Okay now i am editing the question because this is a bad practice..
Okay now i got to know about this is a bad practice so now please give this question to up and I am apologizing for this.
Usually, this is a bad practice. But here you go:
try:
<your code here>
except:
pass
This will try your code and if it fails then does nothing.
Example:
In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results in no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
Does Python has a feature that allows one to evaluate a function or expression and if the evaluation fails (an exception is raised) return a default value.
Pseudo-code:
evaluator(function/expression, default_value)
The evaluator will try to execute the function or expression and return the result is the execution is successful, otherwise the default_value is returned.
I know I create a user defined function using try and except to achieve this but I want to know if the batteries are already included before going off and creating a custom solution.
In order to reuse code, you can create a decorating function (that accepts a default value) and decorate your functions with it:
def handle_exceptions(default):
def wrap(f):
def inner(*a):
try:
return f(*a)
except Exception, e:
return default
return inner
return wrap
Now let's see an example:
#handle_exceptions("Invalid Argument")
def test(num):
return 15/num
#handle_exceptions("Input should be Strings only!")
def test2(s1, s2):
return s2 in s1
print test(0) # "Invalid Argument"
print test(15) # 1
print test2("abc", "b") # True
print test2("abc", 1) # Input should be Strings only!
No, the standard way to do this is with try... except.
There is no mechanism to hide or suppress any generic exception within a function. I suspect many Python users would consider indiscriminate use of such a function to be un-Pythonic for a couple reasons:
It hides information about what particular exception occurred. (You might not want to handle all exceptions, since some could come from other libraries and indicate conditions that your program can't recover from, like running out of disk space.)
It hides the fact that an exception occurred at all; the default value returned in case of an exception might coincide with a valid non-default value. (Sometimes reasonable, sometimes not really so.)
One of the principles of the Pythonic philosophy, I believe, is that "explicit is better than implicit," so Python generally avoids automatic type casting and error recovery, which are features of more "implicit- friendly"languages like Perl.
Although the try... except form can be a bit verbose, in my opinion it has a lot of advantages in terms of clearly showing where an exception may occur and what the control flow is around that exception.
I am developing a program in python and have reached a point I don't know how to solve.
My intention is to use a with statement, an avoid the usage of try/except.
So far, my idea is being able to use the continue statement as it would be used inside the except. However, I don't seem to succeed.
Let's supposse this is my code:
def A(object):
def __enter__:
return self
def __exit__:
return True
with A():
print "Ok"
raise Exception("Excp")
print "I want to get here"
print "Outside"
Reading the docs I have found out that by returning True inside the __exit__ method, I can prevent the exception from passing, as with the pass statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised.
So far I haven't been able to find a way to do this. Any advice would be appreciated.
Thank you very much.
It's not possible.
The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your with block is over.
You can't. The with statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed when exiting it), not to act as Visual Basic's infamous On Error Resume Next.
If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the exception in a try/except statement.
Though most of the answers are correct, I'm afraid none suits my problem (I know I didn't provide my whole code, sorry about that).
I've solved the problem taking another approach. I wanted to be able to handle a NameError ("variable not declared") inside a With. If that occurred, I would look inside my object for that variable, and continue.
I'm now using globals() to declare the variable. It's not the best, but it actually works and let's the with continue as no exception is being risen.
Thank you all!
So this is a little bit of a strange question, but it could be fun!
I need to somehow reliably cause an exception in python. I would prefer it to be human triggered, but I am also willing to embed something in my code that will always cause an exception. (I have set up some exception handling and would like to test it)
I've been looking around and some ideas appear to be division by zero or something along those lines will always cause an exception--Is there a better way? The most ideal would be to simulate a loss of internet connection while the program is running....any ideas would be great!
Have fun!
Yes, there is: You can explicitly raise your own exceptions.
raise Exception("A custom message as to why you raised this.")
You would want to raise an appropriate exception/error for loss of network connectivity.
You can define your own Exceptions in Python, so you can create custom errors to suit your needs. You can test that certain conditions exist, and use the truthiness of that test to decide whether or not to raise your shiny, custom Exception:
class MyFancyException(Exception): pass
def do_something():
if sometestFunction() is True:
raise MyFancyException
carry_on_theres_nothing_to_see()
try:
do_something()
except MyFancyException:
# This is entirely up to you!
# What needs to happen if the exception is caught?
The documentation has some useful examples.
Yup, you can just plop
1 / 0
anywhere in your code for a run time error to occur, specifically in this case a ZeroDivisionError: integer division or modulo by zero.
This is the simplest way to get an exception by embedding something in your code (as you mentioned in your post). You can of course raise your own Exceptions too .. depends on your specific needs.
I'm trying to write code that supports the following semantics:
with scope('action_name') as s:
do_something()
...
do_some_other_stuff()
The scope, among other things (setup, cleanup) should decide if this section should run.
For instance, if the user configured the program to bypass 'action_name' than, after Scope() is evaluated do_some_other_stuff() will be executed without calling do_something() first.
I tried to do it using this context manager:
#contextmanager
def scope(action):
if action != 'bypass':
yield
but got RuntimeError: generator didn't yield exception (when action is 'bypass').
I am looking for a way to support this without falling back to the more verbose optional implementation:
with scope('action_name') as s:
if s.should_run():
do_something()
...
do_some_other_stuff()
Does anyone know how I can achieve this?
Thanks!
P.S. I am using python2.7
EDIT:
The solution doesn't necessarily have to rely on with statements. I just didn't know exactly how to express it without it. In essence, I want something in the form of a context (supporting setup and automatic cleanup, unrelated to the contained logic) and allowing for conditional execution based on parameters passed to the setup method and selected in the configuration.
I also thought about a possible solution using decorators. Example:
#scope('action_name') # if 'action_name' in allowed actions, do:
# setup()
# do_action_name()
# cleanup()
# otherwise return
def do_action_name()
do_something()
but I don't want to enforce too much of the internal structure (i.e., how the code is divided to functions) based on these scopes.
Does anybody have some creative ideas?
You're trying to modify the expected behaviour of a basic language construct. That's never a good idea, it will just lead to confusion.
There's nothing wrong with your work-around, but you can simplify it just a bit.
#contextmanager
def scope(action):
yield action != 'bypass'
with scope('action_name') as s:
if s:
do_something()
...
do_some_other_stuff()
Your scope could instead be a class whose __enter__ method returns either a useful object or None and it would be used in the same fashion.
The following seems to work:
from contextlib import contextmanager
#contextmanager
def skippable():
try:
yield
except RuntimeError as e:
if e.message != "generator didn't yield":
raise
#contextmanager
def context_if_condition():
if False:
yield True
with skippable(), context_if_condition() as ctx:
print "won't run"
Considerations:
needs someone to come up with better names
context_if_condition can't be used without skippable but there's no way to enforce that/remove the redundancy
it could catch and suppress the RuntimeError from a deeper function than intended (a custom exception could help there, but that makes the whole construct messier still)
it's not any clearer than just using #Mark Ransom's version
I don't think this can be done. I tried implementing a context manager as a class and there's just no way to force the block to raise an exception which would subsequently be squelched by the __exit__() method.
I have the same use case as you, and came across the conditional library that someone has helpfully developed in the time since you posted your question.
From the site, its use is as:
with conditional(CONDITION, CONTEXTMANAGER()):
BODY()