Why do we raise exceptions? Can't we use print with sys.exit() ?
The latter will do the same thing. Is there's something I'm missing?
Do "raise" only help while defining a function , so that it won't return "None" in case of failure?
Examples would be appreciated!
Thanks!
There are already multiple good answers on Quora:
https://www.quora.com/Why-do-we-need-to-raise-exception-in-Python-programming-Cant-we-handle-the-same-thing-with-just-if-else-statements
Related
Hello, I think my question is fairly simple so I don't have to write in code format here, I just want to know some intermediates coding practice in blender python,
i just want to know how can i run call this function and then leave out and not running just one line?
For example: self.Grobs = False,
I want to keep this true
I sort of guess the function parenthesis can help in this?
def cul_off_all():
thank you in advance!
Cheers!
I am trying to find complete documentation for cursor.fetchone and all I can find is:
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.CursorStoreResultMixIn-class.html#fetchone
my questions are:
what is exactly returned? a normal python array?
what does it return if there no more rows?
what does it do if the connection is dropped? throw an error? have a unique return value?
I am not sure why I can't find real documentation on this. Thank you in advance
I'll try to answer in order your questions.
What is exactly returned?
A tuple or a dictionary, depending how you did the connection.
What does it return if there no more rows?
None
What does it do if the connection is dropped?
An Exception is raised. If it's due to a timeout, for instance, it will be a MySQLdb.OperationalError.
I am not sure why I can't find real documentation on this
Try here: https://mysqlclient.readthedocs.io/
Here is the code:
from py4j.protocol import Py4JJavaError
def parse_clf_time(s):
try:
#return "{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}".format(int(s[7:11]),month_map[s[3:6]],int(s[0:2]),int(s[12:14]),int(s[15:17]),int(s[18:20]))
return "{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}".format(
int(s[7:11]),
month_map[s[3:6]],
int(s[0:2]),
int(s[12:14]),
int(s[15:17]),
int(s[18:20])
)
except Py4JJavaError as e:
return "2016-08-11 00:00:01".format(
int(s[7:11]),
month_map[s[3:6]],
int(s[0:2]),
int(s[12:14]),
int(s[15:17]),
int(s[18:20])
u_parse_time = udf(parse_clf_time)
final_df = cleaned_df.select('*', u_parse_time(cleaned_df['timestamp']).cast('timestamp').alias('time')).drop('timestamp')
total_log_entries = final_df.count()
The df may contain bad data so I want to use a silly try except to handle it, please let me what is the best practice to exclude bad data.
For unknown reason, I got error:
So what's wrong with the code? It works in another project on the same environment so I am pretty sure the error should not be from the code itself.
Thank you very much, any clue is appreciated.
You missed a ) for return "2016-08-11 00:00:01".format(
Also, you didn't have
from pyspark.sql.functions import udf
missing parentheses or bracket are indeed so common, I would suggest you using a text edit tool for double check in case like this. I use UltraEdit which is great to me.
I have a basic problem in Python where I have to verify if my backtracking code found some solutions (I have to find all sublists of 1 to n numbers with property |x[i] - x[i-1]| == m). How do I check if there is some solution? I mean the potentially solutions I find, I just print them and not save them into memory. I have to print a proper message if there is no solutions.
As I suggested in comment, you might want to dissociate computing from I/O printing, by creating a generator of your solutions of |x[i] - x[i-1]| == m
Let's assume you defined a generator for yielding your solutions:
def mysolutions(...):
....
# Something with 'yield', or maybe not.
....
Here is a generator decorator that you can use to check if an implemented generator has a value
from itertools import chain
def checkGen(generator, doubt):
"""Decorator used to check that we have data in the generator."""
try:
first = next(generator)
except StopIteration:
raise RuntimeError("I had no value!")
return chain([first], generator)
Using this decorator, you can now define your previous solution with :
#checkGen
def mysolutions(...):
....
Then, you can simply use it as is, for dissociating your I/O:
try:
for solution in mysolutions(...):
print(solution) #Probably needs some formatting
except RuntimeError:
print("I found no value (or there was some error somewhere...)")
After reading To ternary or not to ternary? and Is this a reasonable use of the ternary operator?, I gathered that simple uses of the ternary operator are generally accepted, because they do not hurt readability. I also gathered that having one side of the ternary block return null when you don't want it to do something is a complete waste.. However, I ran across this case while refactoring my site that made me wrinkle my nose:
if ($success) {
$database->commit();
} else {
$database->rollback();
}
I refactored this down to
$success ? $database->commit() : $database->rollback();
And I was pretty satisfied with it.. but something inside me made me come here for input. Exception catching aside, would you consider this an okay use case? Am I wondering if this is an okay use because I have never done this before, or because it really is bad practice? This doesn't seem difficult to me, but would this seem difficult to understand for anyone else? Does it depend on the language.. as in, would this be more/less wrong in C, C++, or Java?
No, it is not OK. You are turning something that should look like a statement into something that looks like an expression. In fact, if commit() and rollback() return void, this will not compile in Java at least (not sure about the others mentioned).
If you want a one-liner, you should rather create another method on the $database object such as $database->endTransaction($success) that does the if statement internally.
I would be more inclined to use it in case the two actions are mutually-exclusive and/or opposite (yet related to each other), for example:
$success ? go_up() : go_down();
For two unrelated actions I would be less inclined to use it, the reason being that there is a higher probability for one of the branches to need expanding in the future. If that's the case, you will again need to rewrite it as an if-else statement. Imagine that you have:
$success ? do_abc() : do_xyz();
If at some point you decide that the first branch needs to do_def() as well, you'll need to rewrite the whole thing to an if-else statement again.
The more frequent usage of the ternary operator, however, is:
$var = $success ? UP : DOWN;
This way you are evaluating it as an expression, not as a statement.
The real question is, "Is the ternary form more or less readable than the if form?". I'd say it isn't. But this is a question of style, not of function.