Single Statement Exception Checking [duplicate] - python

This question already has answers here:
How to handle exceptions in a list comprehensions?
(7 answers)
Closed 9 years ago.
I'm just curious if this exists. After programming python for the better part of a year I've never come across it.
Is there a python function that is c-compiled (for faster access in comprehensions) that checks an exception:
A function like the following:
def no_exception(function, *args, **kwargs):
try:
function(*args, **kwargs)
except Exception:
return False
return True
You could use it in this case
# values is full of data
new_values = [float(n) if no_exception(float, n) else n for n in values]

No
at least not in the standard library. Otherwise the assertRaises method in the Python unittest module would use it. See: http://pythonhosted.org/gchecky/unittest-pysrc.html#TestCase.failUnlessRaises
You can of course write your own c implementation easily.

Related

Why doesn't this recursive GCD function work? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 5 months ago.
I'm currently playing with recursive functions and I have a question.
I don't understand why this one work
a, b = map(int, input().split())
def gcd(a,b):
if a%b == 0:
return b
else:
return gcd(b,a%b)
print(gcd(a,b))
but this one doesn't
a, b = map(int, input().split())
def gcd(a,b):
if a%b == 0:
return b
gcd(b,a%b)
print(gcd(a,b))
Though the answer appears in the comments, I thought this is an opportunity to demonstrate how python tools can help you find similar errors like this in the future.
$ pylint --disable=invalid-name,redefined-outer-name,missing-function-docstring,missing-module-docstring main.py
************* Module Downloads.main
main.py:2:0: R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)
-------------------------------------------------------------------
Your code has been rated at 8.33/10 (previous run: 10.00/10, -1.67)
So here you see pylint points your attention to implicit return values from some path(s) in your function. Note that some of pylint's reports (the ones I disabled for instance) may generate "noise" rather than be helpful). Still, using this tool (and mypy and others) may sure help you

"return" and "return None" behavior difference in generator [duplicate]

This question already has answers here:
Return in generator together with yield
(2 answers)
Why can't I use yield with return?
(5 answers)
Closed 3 years ago.
Simple method with just return keyword returns a None
def abc():
return
print(abc())
Output: None
Similarly,
def abc():
return None
print(abc())
Output: None
However if we use this in generator
def abc():
yield 1
return None
print(abc())
it gives
SyntaxError: 'return' with argument inside generator
where as
def abc():
yield 1
return
print(abc())
gives
<generator object abc at 0x7f97d7052b40>
Why do we have this difference in behavior?
A bare return is useful to break out early from a generator.
Meanwhile return None is just a special case of return <a value>, and before yield from (PEP 380) there was no support or use case for returning a value from a generator. So it was forbidden in order to leave the design space open: by forbidding returning values in generators, Python's designers made it possible to allow it later with new semantics as that would not break existing code.
Had they allowed a return value without doing anything with it, there was a risk userland code would break. That's why from a forward-compatibility perspective it's often better to restrict APIs as much as possible, everything you leave open users will take advantage of, and it becomes risky to change.

passing object to object [duplicate]

This question already has answers here:
Can you explain closures (as they relate to Python)?
(13 answers)
Closed 6 years ago.
I am trying to understand the background of why the following works:
def part_string(items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
my_indexes = (2,1)
my_string = 'ABCDEFG'
function_instance = part_string(my_indexes)
print(function_instance(my_string))
# also works: print(part_string(my_indexes)(my_string))
how come I can pass my_string to function_instance object even though I already passed my_indexes attributes to part_string() when creating function_instance? why Python accepts my_string implicitly?
I guess it has something to do with the following, so more questions here:
what is obj in g(obj)? can this be something other e.g. g(stuff) (like with self which is just a convention)?
what if I want to pass 2 objects to function_instance? how do I refer to them in g(obj)?
Can You recommend some reading on this?
What you're encountering is a closure.
When you write part_string(my_indexes) you're creating a new function, and upon calling it, you use the old variables you gave to part_string together with the new variables given to function_instance.
You may name the inner function whatever you want, and there is no convention. (obj is used in here but it can be pie. There are no conventions for this except func for function closures (decorators).
If you wish to pass two variables to the function, you may define two variables to the g(obj) function:
def g(var1, var2):
...
Here's some more info regarding closures in python.

is Python return always necessary [duplicate]

This question already has answers here:
return, return None, and no return at all?
(5 answers)
Closed 7 years ago.
I just stumbled across several python programs written by different people and I noticed that every function had a return at the end of it
def function01():
# function
# events
# here
return
I was wondering if it's good python programming practice to include return at the end of functions even if it is not returning anything (purely as a way of ending the function)
Or is it not needed and nothing different will happen in the background?
No, it is not necessary. The function returns after the last line. There is no difference between a simple return and no return.
def foo():
pass
def bar():
pass
return
f = foo()
print(f)
b = bar()
print(b)
Output:
None
None

wrapper for a multitude of functions to check for existing data [duplicate]

This question already has answers here:
What is memoization and how can I use it in Python?
(14 answers)
Closed 9 years ago.
If it is so, please do not hesitate to close question as duplicate. :)
In my code, I have a lot of blocks that look like
try:
load_from_disk(pathtofile)
except IOError:
datapiece = comp_this_data( **dictofargs )
save_to_disk(pathtofile, datapiece)
Question: How to define a routine that takes care of possible precomputed data for different comp_this_data?
Maybe, this is an easy case for python decorators. However, as I understood, the decorator is part of the function definition, which I don't want to change.
Any ideas?
Here is an example of how you can wrap multiple computation functions:
def compute_and_save(compute_f, file, *args, **kwargs):
try:
load_from_disk(file)
except IOError:
datapiece = compute_f(*args, **kwargs)
save_to_disk(file, datapiece)
if __name__ == "__main__":
compute_and_save(comp_this_data, file, **dictofargs)
compute_and_save(comp_this_data_2, file, **dictofargs)

Categories