pythonic return in try [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
What is the correct way to deal with return of function in try block?
Option 1:
def someFnc1() -> bool:
try:
fetchSomeData()
return True
except:
return False
Option 2:
def someFnc2() -> bool:
try:
fetchSomeData()
except:
return False
return True

This is described in part in PEP-8:
Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
Yes:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
No:
try:
# Too broad!
return handle_value(collection[key])
except KeyError:
# Will also catch KeyError raised by handle_value()
return key_not_found(key)
Based on this your second version should be considered most pythonic (i.e. the absolute minimum of code inside the try clause).

Related

How to convert list of strings into floats? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the list of data:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
I need to convert it into float in order to calculate the average and etc.
I've tried:
list(map(float, rfd_per_neihborhood_15))
list(np.float_(rfd_per_neihborhood_15))
for item in list:
float(item)
a = rfd_per_neihborhood_15
floats = []
for element in a:
floats.append(float(element))
print(floats)
Nothing is working, it's throwing ValueError: could not convert string to float: '-'
The problem could be that there is an element in your list which has a - (hyphen). To tackle that, you can use try-except in the following manner:
rfd_per_neihborhood_15 = ['75.8','108.5','76.6','96.4','104.8','95.8','165.8','128.9','4-4']
def safe_float(x):
try:
return float(x)
except:
print(f"Cannot convert {x}")
#Returning a 0 in case of an error. You can change this based on your usecase
return 0
list(map(safe_float, rfd_per_neihborhood_15))
Output:
Cannot convert 4-4
[75.8, 108.5, 76.6, 96.4, 104.8, 95.8, 165.8, 128.9, 0]
As you can see, my code gracefully handled the exception and returned a 0 in place of the last element '4-4'. Alternatively, you could also return a NaN.
You could try this:
rfd_per_neihborhood_15 = ['75.8', '108.5', '76.6', '96.4', '104.8', '95.8', '165.8', '128.9']
# shortening the name to r_pn15
r_pn15 = rfd_per_neihborhood_15
floated_list = []
for item in r_pn15:
r_pn15.append(float(item))
print(floated_list)

Ugly IF conditions : Which way is preferred for code-readability? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
So for example,
Code A :
def am_I_smart() :
def check_IQ():
return very_less_readable_nested_json["name"]["status"]["brain"]["codenumber"]["wowbad"]["IQ"] > 110
def are_you_ok() :
return very_less_readable_nested_json["name"]["status"]["brain"] == 'OK'
if check_IQ() and are_you_ok() :
return True
return False
Or
Code B:
def am_I_smart() :
if very_less_readable_nested_json["name"]["status"]["brain"]["codenumber"]["wowbad"]["IQ"] > 110
and very_less_readable_nested_json["name"]["status"]["brain"] == 'OK' :
return True
return False
and Maybe Code C:
def am_I_smart() :
person = very_less_readable_nested_json["name"]
brain_status = person["status"]["brain"]
IQ = brain_status["codenumber"]["wowbad"]["IQ"]
if IQ > 110 and brain_status == 'OK' :
return True
return False
Which is probably the most pythonic, or conventional way of dealing with this kind of problem?
Or is there any other preferred way of dealing with nested json-originated dict for readbility?
Code C is the best from a readability point of view. You can also make it a bit more simple using
return IQ > 110 and brain_status == 'OK'
Aside from this it may make accessing the fields nicer and more readable to convert the JSON back into an object, however I would call C and acceptable solution.

Combining two for else block [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two for else block which verifies two integers,Is it possible to combine both together?
for vars in result['events']:
if vars['yyy'] == 977:
break
else:
raise AssertionError('output not found')
for vars in result['events']:
if vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')
With simple or condition:
for vars in result['events']:
if vars['yyy'] == 977 or vars['yyy'] == int(line.split(',')[-1], 16):
break
else:
raise AssertionError('output not found')
Update after condition clarification:
(also line.split(',')[-1] is replaced with line[line.rfind(',') + 1:])
yyy_set = {977, int(line[line.rfind(',') + 1:], 16)}
for vars in result['events']:
vars['yyy'] in yyy_set and yyy_set.remove(vars['yyy'])
if not yyy_set: break # all set items were consumed
else:
raise AssertionError('output not found')
The other answers assume you want to find one of two needles in a single haystack, and don't care which one you find, but the question isn't clear if that's the correct solution.
To cover the case where you need both search values to be found (looking for two different needles in one haystack, and both must exist), there is no easy syntax to do it. But you can build that logic out of a set and for/else:
remaining = {977, int(line.split(',')[-1], 16)}
for vars in result['events']:
remaining.discard(vars['yyy'])
if not remaining:
break
else:
raise AssertionError('Expected outputs not found: {}'.format(remaining))
remaining.discard(vars['yyy']) removes each vars['yyy'] if it exists, and silently ignores it if it does not. When both expected values have been seen (and discarded), the set is empty, and you break, bypassing the else. If one or more values has not been seen, they'll remain in remaining and can be incorporated into the error message.
The question could have a bit clearer that what it is. Based on what I could understand, you are looking for 2 different values in result['events']. You could use 'or' condition to club the 2 conditions together.
if foobar == 'bac' or zoo == '123':
blah
else:
bleh

Linking elements of a list as a tree [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.
You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child
Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

IndentationError on exception handling block [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
def getidxmax(window_2, Filtered):
try: bar = window_2[Filtered].idxmax()
return bar
except ValueError:
return np.nan
Am calling the above function like this:
bar = getidxmax(window_2, Filtered)
But am getting error:
File "<algorithm>", line 22
return bar
^
IndentationError: unexpected indent
line 22 is where the try: begins.
Your syntax for try except isn't perfectly correct.
def getidxmax(window_2, Filtered):
try:
return (window_2[Filtered]).idxmax()
except ValueError:
return np.nan
You don't need to create a new variable bar, you can just try and return the result of window_2[Filtered].idmax() and if that fails, np.nan
def getidxmax(window_2, Filtered):
try:
bar = window_2[Filtered].idxmax()
return bar
except ValueError:
return np.nan

Categories

Resources