Can someone please explain me why does this work like it does? Python 3.6.3  In [1]: def test():    ...:     try:    ...:         return 1    ...:     finally:    ...:         return 2    ...:       In [2]: test() Out[2]: 2   EDIT: This is not exactly duplicate as linked questions raise exceptions in their try : and my example uses return which I expected to work. This function looks like it should return 1 yet it returns 2 - so basically return 1 is ignored. finally makes a good job of eating any risen exceptions but should it also eat returns?
85902
I found the following behavior at least weird:  def errors():     try:         ErrorErrorError     finally:         return 10  print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined   The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?  But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
11827
In a comment on this , someone said that they weren't sure what functools.wraps was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?
2178
Why doesn't the following work (Python 2.5.2)?  &gt;&gt;&gt; import datetime &gt;&gt;&gt; class D(datetime.date):         def __init__(self, year):             datetime.date.__init__(self, year, 1, 1) &gt;&gt;&gt; D(2008) Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: function takes exactly 3 arguments (1 given)   I wanted to create a class that was just like datetime.date, but with a different __init__ function.  Apparently my function never gets called.  Instead the original datetime.date.__init__ is called and fails because that expects 3 arguments and I am passing in one.  What's going on here?  And is this a clue?  &gt;&gt;&gt; datetime.date.__init__ &lt;slot wrapper '__init__' of 'object' objects&gt;   Thanks!
118194
I've seen the following code many times:  try {     ... // some code } catch (Exception ex) {     ... // Do something     throw new CustomException(ex);      // or     // throw;      // or     // throw ex; }   Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
116916
To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:  with open("a.txt") as f:     print f.readlines()   I really want to handle 'file not found exception' in order to do somehing. But I can't write  with open("a.txt") as f:     print f.readlines() except:     print 'oops'   and can't write  with open("a.txt") as f:     print f.readlines() else:     print 'oops'   enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?
13479
Note that this function does not have a "{" and "}" body.  Just a try/catch block:  void func( void ) try {     ... } catch(...) {     ... }   Is this intentionally part of C++, or is this a g++ extension?  Is there any purpose to this other than bypass 1 level of {}?  I'd never heard of this until I ran into
95092
Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this?  To me it looks cleaner to deal with special values, rather than exceptions.  EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?
36942
Say I have a Python function that returns multiple values in a tuple:  def func():     return 1, 2   Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:  x, temp = func()
41914
Consider:  int testfunc1 (const int a) {   return a; }  int testfunc2 (int const a) {   return a; }   Are these two functions the same in every aspect or is there a difference?  I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.
98177
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.  Is there a more elegant way of doing this? Perhaps an API call that will reveal this?  Here's some rough code of what I'm talking about:  Throwable t = null;  try {       stream.write(buffer);  } catch(IOException e) {     t = e;   //Need to save this exception for finally     throw e; } finally {        try {        stream.close();   //may throw exception    } catch(IOException e) {       //Is there something better than saving the exception from the exception block?       if(t!=null) {          //propagate the read exception as the "cause"--not great, but you see what I mean.          throw new IOException("Could not close in finally block: " + e.getMessage(),t);       } else {          throw e;  //just pass it up       }        }//end close }   Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.  Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?  This question actually spawned from comments in  that raised an interesting question.
5559
I have a function where I need to do something to a string.  I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.    In C#, I would use an out parameter for the string, but there is no equivalent in Python.  I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.  Related question:
37260
In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks.  For example, the following code does not compile:  try {   String s = "test";   // (more code...) } catch {   Console.Out.WriteLine(s);  //Java fans: think "System.out.println" here instead }   In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block.  (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".)  The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block:  String s; try {   s = "test";   // (more code...) } catch {   Console.Out.WriteLine(s);  //Java fans: think "System.out.println" here instead }   However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally).  My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)?
114724
I'm trying to iterate through an array of elements. jQuery's documentation says:       Returning non-false is the same as a continue statement in a for loop, it will skip immediately to the next iteration.   I've tried calling 'return non-false;' and 'non-false;' (sans return) neither of which skip to the next iteration. Instead, they break the loop. What am i missing?
38527
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the .  However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)  Here's an example:  class A(object):     _dict = dict()      def __new__(cls):         if 'key' in A._dict:             print "EXISTS"             return A._dict['key']         else:             print "NEW"             return super(A, cls).__new__(cls)      def __init__(self):         print "INIT"         A._dict['key'] = self         print ""  a1 = A() a2 = A() a3 = A()   Outputs:  NEW INIT  EXISTS INIT  EXISTS INIT   Why?
123111
I just came across this idiom in some open-source Python, and I choked on my drink.  Rather than:  if isUp:     return "Up" else:     return "Down"   or even:  return "Up" if isUp else "Down"   the code read:  return isUp and "Up" or "Down"   I can see this is the same result, but is this a typical idiom in Python? If so, is it some performance hack that runs fast? Or is it just a once-off that needs a code review?
106949
I'd love some other opinions on what's more efficient in this code. Basically in the following code, there's a setInterval loop and I need 4 requirements to be true before the code runs in the loop. So in v.1 I wrote an if statement checking all 4. Worked fine.  Then I switched to just using try/catch, with the code I want to execute sitting in try{}. The logic was that during each loop, an exception would be generated but suppressed for each invalid condition. On the final loop where all conditions are true, the code executes and clears the interval.  Either works. I like the try/catch method because there's less conditional code that I need to write and worry about breaking. But I'm worried that try/catch is really inefficient, especially in a setInterval() loop hitting at 100ms. What are some opinions of other bright minds here on SO?  Try/Catch  var intvar = setInterval(function(){ try{         clearInterval(intvar);      jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }catch(err){} },100);   IF Block  var intvar = setInterval(function(){  if(typeof jQuery == 'function' &amp;&amp; typeof nav == 'object' &amp;&amp; typeof pageid != 'undefined' &amp;&amp; typeof document.getElementById('leftnav') == 'object'){     clearInterval(intvar);     jQuery('#'+nav[pageid].t1+'&gt;a').replaceWith(jQuery('&lt;span&gt;'+jQuery('#'+nav[pageid].t1+'&gt;a').text()+'&lt;/span&gt;'));      //set display classes for nav     jQuery('#'+nav[pageid].t1).addClass('selected').find('#'+nav[pageid].t2).addClass('subselect'); //topnav     jQuery('#'+nav[pageid].t3).addClass('selected').find('#'+nav[pageid].t4).addClass('subselect'); //leftnav }  },100);
5812
Why does the  exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?  For instance the following example:  Class1 obj = new Class1();  Class1 foo() {     return new Class1(); }   Is as easy to read as the more Pythonesque way of writing it:  Class1 obj = Class1();  Class1 foo() {     return Class1(); }   EDIT:  hit the nail on the head with the clarification of the question: Why did they choose this syntax?