I often have functions that return multiple outputs which are structured like so:
def f(vars):
...
if something_unexpected():
return None, None
...
# normal return
return value1, value2
In this case, there might be a infrequent problem that something_unexpected detects (say, a empty dataframe when the routine expects at least one row of data), and so I want to return a value to the caller that says to ignore the output and skip over it. If this were a single return function then returning None once would seem fine, but when I'm returning multiple values it seems sloppy to return multiple copies of None just so the caller has the right number of arguments to unpack.
What are some better ways of coding up this construct? Is simply having the caller use a try-except block and the function raising an exception the way to go, or is there another example of good practice to use here?
Edit: Of course I could return the pair of outputs into a single variable, but then I'd have to call the function like
results = f(inputs)
if results is None:
continue
varname1, varname2 = results[0], results[1]
rather than the more clean-seeming
varname1, varname2 = f(inputs)
if varname1 is None:
continue
Depends on where you want to handle this behavior, but exceptions are a pretty standard way to do this. Without exceptions, you could still return None, None:
a, b = f(inputs)
if None in (a, b):
print("Got something bad!")
continue
Though, I think it might be better to raise in your function and catch it instead:
def f():
if unexpected:
raise ValueError("Got empty values")
else:
return val1, val2
try:
a, b = f()
except ValueError:
print("bad behavior in f, skipping")
continue
The best practice is to raise an exception:
if something_unexpected():
raise ValueError("Something unexpected happened")
REFERENCES:
Explicit is better than implicit.
Errors should never pass silently.
Unless explicitly silenced.
PEP 20 -- The Zen of Python
I'm using Spyder to create a web scraper, and things are moving smoothly so far. As a rookie, Spyder's Code Analysis function is something I find useful for improving the standard of my code. However, while I usually understand its instructions/recommendations, I've recently run into a bit of a blip. I'll post some sample code first:
def payments(): #### This is line 59 on the editor. Preceding it is another function with a a format similar to this one.
"""Obtains data on the weekly payments in the country"""
html = get(source["Payments"]).text
html = bs(html,"lxml")
location = "/home/oduduwa/Desktop/Python Projects/Financial Analyser/CBN Data/Payments.csv"
def file_check():
headings = [i.text for i in html.find_all(width="284")][:10]
headings.insert(0, "Date")
if isfile(location) is False:
with open(location,"w") as file_obj:
writer(file_obj).writerow(headings)
return
file_check()
file = open(location,"r").read()
dates = [i.text.strip()[8:] for i in html.find_all("th",colspan="2")]
values = [i.text.strip()[4:] for i in html.find_all(width="149") if i.text.strip()[4:]!=""]
values = array(values).reshape(int(len(values)/10),10)
values = insert(values,0,array(dates).transpose(),axis=1)[::-1]
for i in range(len(values)):
if values[i][0] not in file:
with open(location,"a+",newline=("\n")) as file_obj:
writer(file_obj).writerow(values[i])
return
The code runs fin and does everything it should. What I don't really understand, however, is Spyder's statement that there's a useless return call in the code block. Here's what it says specifically:
But from what I gather, every function call is necessary in this coding block. What could I have missed? Thanks for your time!
Python functions implicitly return None by default. The following function definitions are equivalent.
def foo():
pass
def foo():
return
def foo():
return None
In my opinion, it is good practice to either
have no return statement at all - this indicates that you are not supposed to assign a name to the return value when calling the function, or
explicitly return None, to indicate "no result" for a function that could return a meaningful value, or
use just return to make a function that returns no meaningful value stop execution.
Example for situation 1:
def switch_first_last_in_place(lst):
'switch the first and last elements of a list in-place'
lst[0], lst[-1] = lst[-1], lst[0]
This function implicitly returns None and you are not supposed to issue
result = switch_first_last_in_place([1, 2, 3])
Example for situation 2:
def get_user_info_from_database(username):
'fetches user info, returns None if user does not exist'
if user_exist(username):
return query_db(username)
else:
return None
This function explicitly returns None to indicate a user was not found. Assignments like
result = get_user_info_from_database('Bob')
are expected. The part
else:
return None
is unnecessary but I like being explicit in cases where None is a meaningful return value.
Example for situation 3:
def assert_exists(thing, *containers):
'raise AssertionError if thing cannot be found in any container'
for container in containers:
if thing in container:
return
raise AssertionError
Here, return is merely used to break out of the function.
I don't like the bare return at the end of the functions in your example. It is not used to end execution and those functions cannot return other values. I would remove it.
You've misunderstood. The warning isn't talking about any of the functions you are calling. It's referring to your use of the return keyword.
This function:
def print_hello():
print("Hello")
return
Is equivalent to this function:
def print_hello():
print("Hello")
return None
Which is equivalent to this function:
def print_hello():
print("Hello")
The warning is saying, that your return statements are useless, and are not required.
Consider this simple code, which stores a few properties of a MyClass() object in a list:
c = MyClass()
props = [c.property1, c.property2, ..., c.propertyN]
Now, under the hood, c.property1..N are realized as #property-decorated getter functions, which may raise exceptions during execution. In that case, I want to use a default value ('n/a') in the list assignment, instead of the inaccessible property value.
But I don't want to skip the entire list assignment altogether. So, if only c.property2 causes an exception, the result should still be:
props = ['value_of_property1', 'n/a', ..., 'value_of_propertyN']
So I cannot wrap the try-except around the entire list assignment:
c = MyClass()
try:
props = [c.property1, c.property2, ..., c.propertyN]
except MyException:
props = # yes, what?
Of course I could try-except for each element individually:
c = MyClass()
props = []
try:
props.append(c.property1)
except MyException:
props.append('n/a')
try:
props.append(c.property2)
except MyException:
props.append('n/a')
# repeated N times
... but this bloats the code and doesn't feel right.
Is there some sort of inline exception handling?
Perhaps similar these inline if-else statements:
props = [c.property1 if len(c.property1) else 'n/a',
c.property2 if len(c.property2) else 'n/a',
...
c.propertyN if len(c.propertyN) else 'n/a',
]
Notes:
I have full control over the code for MyClass() and the getter functions.
Modifying the getter functions to handle exceptions internally and return a default value straight away is not an option, because in other situations I want to know (via exception...) if the property is accessible or not. Otherwise how could I tell if 'n/a' was the true value of a property or the replaced default (fallback) value?
I have the same problem in print statements using (N*'{};').format(c.property1, c.property2, ..., c.propertyN)
There is no inline exception handling, but there's something better: loops. None of your code is DRY, but that's easily fixed with a loop:
c = MyClass()
props = []
prop_names = ['property1', 'property2', ...]
for prop_name in prop_names:
try:
value = getattr(c, prop_name)
except MyException:
value = 'n/a'
props.append(value)
If you need to do something more complex than just access an attribute, you can replace the list of property names with a list of functions:
c = MyClass()
props = []
getters = [lambda c: c.property1, lambda c: c.property2, ...]
for getter in getters:
try:
value = getter(c)
except MyException:
value = 'n/a'
props.append(value)
The problem
I have the following list in Python 3.6
Piko = {}
Piko['Name']='Luke'
I am trying to write a function that give the value of the element if it exist and is set and give None otherwise.
For example:
INPUT: isset(Piko['Name']) OUTPUT: Luke
INPUT: isset(Piko['Surname']) OUTPUT: None
What I have tried
1st try; based on my know how:
def isset1(x):
try:
x
except KeyError:
print(None)
else:
print(x)
2nd try; based on this answer:
def isset2(x):
try:
t=x
except IndexError:
print(None)
3rd try; based on this answer:
def isset3(x):
try:
x
except Exception:
print(None)
else:
print(x)
Any one of the previous gives me KeyError: 'Surname' error and does not output None as I wanted. Can anybody help me explaining how could I manage correctly the KeyError?
Piko.get('Surname')
Piko.get('Surname', None)
are identical and return None since "Surname" is not in your dictionary.
For future reference you can quickly discover this from the Python shell (eg ipython) by typing:
In[4]: help(Piku.get)
Which produces:
Help on built-in function get:
get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
The exception is happening before it even gets into your isset function. When you do this:
isset(Piko['Name'])
… it's basically the same as doing this:
_tmp = Piko['Name']
isset(_tmp)
No matter what code you put inside isset, it's not going to help, because that function never gets called. The only place you can put the exception handling is one level up, in the function that calls isset.
Or, alternatively, you can not try to lookup dict[key] to pass into isset, and pass the dict and the key as separate parameters:
def isset(d, key):
try:
print(d[key])
except KeyError:
print(None)
But at this point, you're just duplicating dict.get in a clumsier way. You can do this:
def isset(d, key):
print(d.get(key, None))
… or just scrap isset and do this:
print(Piko.get('Name', None))
Or, since None is the default if you don't specify anything:
print(Piko.get('Name'))
This is a follow-up to Handle an exception thrown in a generator and discusses a more general problem.
I have a function that reads data in different formats. All formats are line- or record-oriented and for each format there's a dedicated parsing function, implemented as a generator. So the main reading function gets an input and a generator, which reads its respective format from the input and delivers records back to the main function:
def read(stream, parsefunc):
for record in parsefunc(stream):
do_stuff(record)
where parsefunc is something like:
def parsefunc(stream):
while not eof(stream):
rec = read_record(stream)
do some stuff
yield rec
The problem I'm facing is that while parsefunc can throw an exception (e.g. when reading from a stream), it has no idea how to handle it. The function responsible for handling exceptions is the main read function. Note that exceptions occur on a per-record basis, so even if one record fails, the generator should continue its work and yield records back until the whole stream is exhausted.
In the previous question I tried to put next(parsefunc) in a try block, but as turned out, this is not going to work. So I have to add try-except to the parsefunc itself and then somehow deliver exceptions to the consumer:
def parsefunc(stream):
while not eof(stream):
try:
rec = read_record()
yield rec
except Exception as e:
?????
I'm rather reluctant to do this because
it makes no sense to use try in a function that isn't intended to handle any exceptions
it's unclear to me how to pass exceptions to the consuming function
there going to be many formats and many parsefunc's, I don't want to clutter them with too much helper code.
Has anyone suggestions for a better architecture?
A note for googlers: in addition to the top answer, pay attention to senderle's and Jon's posts - very smart and insightful stuff.
You can return a tuple of record and exception in the parsefunc and let the consumer function decide what to do with the exception:
import random
def get_record(line):
num = random.randint(0, 3)
if num == 3:
raise Exception("3 means danger")
return line
def parsefunc(stream):
for line in stream:
try:
rec = get_record(line)
except Exception as e:
yield (None, e)
else:
yield (rec, None)
if __name__ == '__main__':
with open('temp.txt') as f:
for rec, e in parsefunc(f):
if e:
print "Got an exception %s" % e
else:
print "Got a record %s" % rec
Thinking deeper about what would happen in a more complex case kind of vindicates the Python choice of avoiding bubbling exceptions out of a generator.
If I got an I/O error from a stream object the odds of simply being able to recover and continue reading, without the structures local to the generator being reset in some way, would be low. I would somehow have to reconcile myself with the reading process in order to continue: skip garbage, push back partial data, reset some incomplete internal tracking structure, etc.
Only the generator has enough context to do that properly. Even if you could keep the generator context, having the outer block handle the exceptions would totally flout the Law of Demeter. All the important information that the surrounding block needs to reset and move on is in local variables of the generator function! And getting or passing that information, though possible, is disgusting.
The resulting exception would almost always be thrown after cleaning up, in which case the reader-generator will already have an internal exception block. Trying very hard to maintain this cleanliness in the brain-dead-simple case only to have it break down in almost every realistic context would be silly. So just have the try in the generator, you are going to need the body of the except block anyway, in any complex case.
It would be nice if exceptional conditions could look like exceptions, though, and not like return values. So I would add an intermediate adapter to allow for this: The generator would yield either data or exceptions and the adapter would re-raise the exception if applicable. The adapter should be called first-thing inside the for loop, so that we have the option of catching it within the loop and cleaning up to continue, or breaking out of the loop to catch it and and abandon the process. And we should put some kind of lame wrapper around the setup to indicate that tricks are afoot, and to force the adapter to get called if the function is adapting.
That way each layer is presented errors that it has the context to handle, at the expense of the adapter being a tiny bit intrusive (and perhaps also easy to forget).
So we would have:
def read(stream, parsefunc):
try:
for source in frozen(parsefunc(stream)):
try:
record = source.thaw()
do_stuff(record)
except Exception, e:
log_error(e)
if not is_recoverable(e):
raise
recover()
except Exception, e:
properly_give_up()
wrap_up()
(Where the two try blocks are optional.)
The adapter looks like:
class Frozen(object):
def __init__(self, item):
self.value = item
def thaw(self):
if isinstance(value, Exception):
raise value
return value
def frozen(generator):
for item in generator:
yield Frozen(item)
And parsefunc looks like:
def parsefunc(stream):
while not eof(stream):
try:
rec = read_record(stream)
do_some_stuff()
yield rec
except Exception, e:
properly_skip_record_or_prepare_retry()
yield e
To make it harder to forget the adapter, we could also change frozen from a function to a decorator on parsefunc.
def frozen_results(func):
def freezer(__func = func, *args, **kw):
for item in __func(*args, **kw):
yield Frozen(item)
return freezer
In which case we we would declare:
#frozen_results
def parsefunc(stream):
...
And we would obviously not bother to declare frozen, or wrap it around the call to parsefunc.
Without knowing more about the system, I think it's difficult to tell what approach will work best. However, one option that no one has suggested yet would be to use a callback. Given that only read knows how to deal with exceptions, might something like this work?
def read(stream, parsefunc):
some_closure_data = {}
def error_callback_1(e):
manipulate(some_closure_data, e)
def error_callback_2(e):
transform(some_closure_data, e)
for record in parsefunc(stream, error_callback_1):
do_stuff(record)
Then, in parsefunc:
def parsefunc(stream, error_callback):
while not eof(stream):
try:
rec = read_record()
yield rec
except Exception as e:
error_callback(e)
I used a closure over a mutable local here; you could also define a class. Note also that you can access the traceback info via sys.exc_info() inside the callback.
Another interesting approach might be to use send. This would work a little differently; basically, instead of defining a callback, read could check the result of yield, do a lot of complex logic, and send a substitute value, which the generator would then re-yield (or do something else with). This is a bit more exotic, but I thought I'd mention it in case it's useful:
>>> def parsefunc(it):
... default = None
... for x in it:
... try:
... rec = float(x)
... except ValueError as e:
... default = yield e
... yield default
... else:
... yield rec
...
>>> parsed_values = parsefunc(['4', '6', '5', '5h', '22', '7'])
>>> for x in parsed_values:
... if isinstance(x, ValueError):
... x = parsed_values.send(0.0)
... print x
...
4.0
6.0
5.0
0.0
22.0
7.0
On it's own this is a bit useless ("Why not just print the default directly from read?" you might ask), but you could do more complex things with default inside the generator, resetting values, going back a step, and so on. You could even wait to send a callback at this point based on the error you receive. But note that sys.exc_info() is cleared as soon as the generator yields, so you'll have to send everything from sys.exc_info() if you need access to the traceback.
Here's an example of how you might combine the two options:
import string
digits = set(string.digits)
def digits_only(v):
return ''.join(c for c in v if c in digits)
def parsefunc(it):
default = None
for x in it:
try:
rec = float(x)
except ValueError as e:
callback = yield e
yield float(callback(x))
else:
yield rec
parsed_values = parsefunc(['4', '6', '5', '5h', '22', '7'])
for x in parsed_values:
if isinstance(x, ValueError):
x = parsed_values.send(digits_only)
print x
An example of a possible design:
from StringIO import StringIO
import csv
blah = StringIO('this,is,1\nthis,is\n')
def parse_csv(stream):
for row in csv.reader(stream):
try:
yield int(row[2])
except (IndexError, ValueError) as e:
pass # don't yield but might need something
# All others have to go up a level - so it wasn't parsable
# So if it's an IOError you know why, but this needs to catch
# exceptions potentially, just let the major ones propogate
for record in parse_csv(blah):
print record
I like the given answer with the Frozen stuff. Based on that idea I came up with this, solving two aspects I did not yet like. The first was the patterns needed to write it down. The second was the loss of the stack trace when yielding an exception. I tried my best to solve the first by using decorators as good as possible. I tried keeping the stack trace by using sys.exc_info() instead of the exception alone.
My generator normally (i.e. without my stuff applied) would look like this:
def generator():
def f(i):
return float(i) / (3 - i)
for i in range(5):
yield f(i)
If I can transform it into using an inner function to determine the value to yield, I can apply my method:
def generator():
def f(i):
return float(i) / (3 - i)
for i in range(5):
def generate():
return f(i)
yield generate()
This doesn't yet change anything and calling it like this would raise an error with a proper stack trace:
for e in generator():
print e
Now, applying my decorators, the code would look like this:
#excepterGenerator
def generator():
def f(i):
return float(i) / (3 - i)
for i in range(5):
#excepterBlock
def generate():
return f(i)
yield generate()
Not much change optically. And you still can use it the way you used the version before:
for e in generator():
print e
And you still get a proper stack trace when calling. (Just one more frame is in there now.)
But now you also can use it like this:
it = generator()
while it:
try:
for e in it:
print e
except Exception as problem:
print 'exc', problem
This way you can handle in the consumer any exception raised in the generator without too much syntactic hassle and without losing stack traces.
The decorators are spelled out like this:
import sys
def excepterBlock(code):
def wrapper(*args, **kwargs):
try:
return (code(*args, **kwargs), None)
except Exception:
return (None, sys.exc_info())
return wrapper
class Excepter(object):
def __init__(self, generator):
self.generator = generator
self.running = True
def next(self):
try:
v, e = self.generator.next()
except StopIteration:
self.running = False
raise
if e:
raise e[0], e[1], e[2]
else:
return v
def __iter__(self):
return self
def __nonzero__(self):
return self.running
def excepterGenerator(generator):
return lambda *args, **kwargs: Excepter(generator(*args, **kwargs))
(I answered the other question linked in the OP but my answer applies to this situation as well)
I have needed to solve this problem a couple of times and came upon this question after a search for what other people have done.
One option- which will probably require refactoring things a little bit- would be to simply create an error handling generator, and throw the exception in the generator (to another error handling generator) rather than raise it.
Here is what the error handling generator function might look like:
def err_handler():
# a generator for processing errors
while True:
try:
# errors are thrown to this point in function
yield
except Exception1:
handle_exc1()
except Exception2:
handle_exc2()
except Exception3:
handle_exc3()
except Exception:
raise
An additional handler argument is provided to the parsefunc function so it has a place to put the errors:
def parsefunc(stream, handler):
# the handler argument fixes errors/problems separately
while not eof(stream):
try:
rec = read_record(stream)
do some stuff
yield rec
except Exception as e:
handler.throw(e)
handler.close()
Now just use almost the original read function, but now with an error handler:
def read(stream, parsefunc):
handler = err_handler()
for record in parsefunc(stream, handler):
do_stuff(record)
This isn't always going to be the best solution, but it's certainly an option, and relatively easy to understand.
About your point of propagating exception from generator to consuming function,
you can try to use an error code (set of error codes) to indicate the error.
Though not elegant that is one approach you can think of.
For example in the below code yielding a value like -1 where you were expecting
a set of positive integers would signal to the calling function that there was
an error.
In [1]: def f():
...: yield 1
...: try:
...: 2/0
...: except ZeroDivisionError,e:
...: yield -1
...: yield 3
...:
In [2]: g = f()
In [3]: next(g)
Out[3]: 1
In [4]: next(g)
Out[4]: -1
In [5]: next(g)
Out[5]: 3
Actually, generators are quite limited in several aspects. You found one: the raising of exceptions is not part of their API.
You could have a look at the Stackless Python stuff like greenlets or coroutines which offer a lot more flexibility; but diving into that is a bit out of scope here.