News for hackers. Stuff that matters.
Re:Why I’m not leaving Python for Go by cletus on Monday September 24, 2012 @03:05AM (#4563544)
I have mixed feelings about errors as return codes. Then again, I have mixed feelings about exceptions.

There are two general use cases for exceptions:

1. Unexpected (typically fatal) problems;

2. As an alternative to multiple return values.

(1) is things like out of memory errors. (2) is things like you're trying to parse a user input into a number and it fails. I despise (2) for exceptions. It means writing code like:

    try:
      f = float(someText)
    catch ValueError:
      # I just parsed you, this is crazy,
      # here's an exception, throw it maybe?
where this gets particularly irritating is when you start writing code like this:

    try:
      doSomething()
    catch ValueError:
      pass
I nearly always end up writing wrapper functions around that crap.

Java is worse for this because some libraries (including standard ones) abuse checked exceptions for this. I actually prefer:

    if f, err := strconv.ParseFloat(text); err != nil {
      // do something
    }
or even:

    f, _ := strconv.ParseFloat(text);
for this kind of scenario.

For the truly bad--typically fatal--error conditions and cleanup, IMHO defer/panic actually works quite well. I certainly prefer this:

    f := File.Open('foo')
    defer f.Close()
    // do stuff
to:

    try:
      f = open('foo')
      # do stuff
    finally:
      if f:
        f.close()
as Go puts the two relevant things together.

Don't get me wrong: I like Python too but I do think Go has a lot going for it and has a bright future.

Re:Why I’m not leaving Python for Go by gnuvince on Monday September 24, 2012 @06:14AM (#4563946)
One problem with Go is that is uses multiple return values to indicate errors instead of alternative return values. When you call strconv.ParseFloat, you always get back two values, the error code and... wait, what float do you get back when there's an error?

If you're going to use return values to indicate errors (and certainly I feel that there are reasons to use them, exceptions vs error codes is not an either/or proposition IMO), you should use sum types and return either an error or the correct value and have a mechanism to make sure you handle both cases.

ML and Haskell get this right, it's a shame Go overlooked them in this regard.

Re:Why I’m not leaving Python for Go by _ak on Monday September 24, 2012 @08:38AM (#4564307)
> One problem with Go is that is uses multiple return values to indicate errors instead of alternative return values. When you call strconv.ParseFloat, you always get back two values, the error code and... wait, what float do you get back when there's an error?

Why would you even be interested in the float when there's an error?

Re:Why I’m not leaving Python for Go by masklinn on Monday September 24, 2012 @08:59AM (#4564380)
That's his point: why do you get something typed as float back when there's an error? And what does that thing mean?
Re:Why I’m not leaving Python for Go by _ak on Monday September 24, 2012 @10:26AM (#4564818)
But if there was an error, WHY WOULD YOU EVEN BOTHER?! Read the documentation what it says about the value in case of an error, and stop inflating a non-issue.
Re:Why I’m not leaving Python for Go by papsosouid on Monday September 24, 2012 @10:57AM (#4564979)
Human beings are capable of making mistakes, that's the entire point. If you forgot to check the error code in go, then you will end up using that non-float float that shouldn't exist as if it were really a float. In a decent language, you get either an error or a float, you have no way to accidently use the float if an error occurred.
Re:Why I’m not leaving Python for Go by _ak on Monday September 24, 2012 @03:19PM (#4566424)
> If you forgot to check the error code in go, then you will end up using that non-float float that shouldn't exist as if it were really a float.

Consider the following code:

   foo, err := strconv.ParseFloat(...)
If you don't handle the error (e.g. by forgetting), the compiler will show an error because you declared err, but didn't use it.

If you write

    foo, _ := strconv.ParseFloat(...)
instead, you deliberately choose to ignore the error.

> In a decent language, you get either an error or a float, you have no way to accidently use the float if an error occurred.

Making these specifics a criteria for decency is nothing but arrogance.

Re:Why I’m not leaving Python for Go by papsosouid on Monday September 24, 2012 @05:40PM (#4567152)
>If you don't handle the error (e.g. by forgetting), the compiler will show an error because you declared err, but didn't use it.

But if I make a mistake like I mentioned previously, I could very well use err, thus not getting a compiler warning, and still also use foo, which is a whoknowswhat. It should be an Either, not two seperate return values.

>Making these specifics a criteria for decency is nothing but arrogance.

Having opinions is not arrogance. You should consider that when someone shares their opinion, they are not declaring that everyone everywhere must acknowledge it as a universal truth.

Re:Why I’m not leaving Python for Go by Evbn on Monday September 24, 2012 @11:10PM (#4568356)
And in Haskell you could make the mistake of ignoring the error and writing

  Right x = leftOrRight y
And get a runtime crash when a Left shows up,

  Or
  Just x = justOrNone y
And crash on None.
Re:Why I’m not leaving Python for Go by gnuvince on Tuesday September 25, 2012 @12:56AM (#4568660)
As you point out, in both cases the program will crash, which for many people is preferable to the program churning along with invalid data. In Go with multiple return values, it is possible to have a code path where there's an error but still use what would've been the result of the procedure. In ML or Haskell when using sum types, that code path does not exist.
Re:Why I’m not leaving Python for Go by masklinn on Tuesday September 25, 2012 @03:46AM (#4569155)
> In ML or Haskell when using sum types, that code path does not exist.

Of course it exists: don't unpack the result and ignore it or pass it along, or use it through its monadic or applicative interface (to proxy-with-transform to the caller).

Re:Why I’m not leaving Python for Go by gnuvince on Tuesday September 25, 2012 @10:50AM (#4570623)
I feel we may be arguing without me having properly defined what I meant, so I will try to remedy this. Consider the following code:

    a, _ := some_computation_that_may_fail()
    b := f(a)
In Go, if there was an error in `some_computation_that_may_fail`, the call to `f` will be made with a undetermined value for `a` and we end up with an undetermined value for `b`. This is why I say that there is a path where we can use `a` even when we shouldn't.

Compare with OCaml:

    let Some a = some_computation_that_may_fail () in
    let b = f a
First of all, the compiler will warn you that the pattern matching on line 1 is non-exhaustive and will give you an example of a failing case (here, it will simply be `None`). If the programmer ignores that warning and runs the program anyway and the computation executes with an error, the program will fail at the first line, and thus the second function `f` will never be called and `b` will not contain an undetermined value.

I hope this clears up what I meant, I apologize that I wasn't clearer in the first place. Cheers!

Re:Why I’m not leaving Python for Go by papsosouid on Tuesday September 25, 2012 @09:25AM (#4570175)
I don't know what you mean by your first example, how does that lead to using undefined data? And your second example is incorrect, if you use an Either in monadic style then each successive function call after the error occurs is doing nothing. It simply returns the existing error from the Either, it doesn't try to run a computation on the non-existent value.
Re:Why I’m not leaving Python for Go by papsosouid on Tuesday September 25, 2012 @09:21AM (#4570151)
That isn't the same. If you do that you will get an Irrefutable pattern failed exception. You don't actually get access to x if justOrNone returns Nothing, because you are pattern matching and the Just pattern doesn't match. So you won't be able to use a non-value in further computations like you can with go.
Re:Why I’m not leaving Python for Go by ubershmekel on Monday September 24, 2012 @04:33AM (#4563750)
I agree that exceptions can be cumbersome at times. And I do prefer the Go parsing float example to the try/catch one if my entire program is only one line.

But in order to live in peace you have to either:

* Force every programmer to always check all the error values.

or

* Allow errors to pass silently.

So either you accept Go as a heavy-duty, heavy boilerplate error handling laden language. Or you accept it as a flaky, risky language.

Exceptions are the better compromise in my opinion. You get much cleaner code.

If this is the more common pattern for your programming life:

    try:
        f = float(someText)
        use_it_here(f)
        use_it_there(f)
    catch Exception:
        # I wanted to do things, but something went wrong.
        # Here's what to do now, this is easy
Then you're better off using exceptions. If you need to check every single call (e.g. NASA or Kernel programming) then you might prefer this:

    if f, err := strconv.ParseFloat(text); err != nil {
      // do something
    }
    if f, err := use_it_here(text); err != nil {
      // do something
    }
    if f, err := use_it_there(text); err != nil {
      // do something
    }
Re:Why I’m not leaving Python for Go by nickbp on Monday September 24, 2012 @05:27AM (#4563864)
So, I rarely see eg Java code that actually handles the exceptions it receives. Usually its just "Oh, I got an exception, so I'll print an error (or silently fail) and blindly keep going".

Given this, I don't see how Go is any worse with respect to sloppy programmers. They'll Always Find A Way.

Also, why couldn't your second example be nested? It seems like either of those two examples could be structured identically to the other.

Re:Why I’m not leaving Python for Go by ubershmekel on Monday September 24, 2012 @07:14AM (#4564052)

    Errors should never pass silently
    Unless explicitly silenced
The problem with go is that you have 3 error modes:

1. Explicitly handle everything

2. Implicitly silence sometimes

3. Panic/recover explodes sometimes (who knows where/when?)

Mode #2 is dangerous.

Java/Python give you 2 only modes:

1. Implicitly explode on error.

2. Explicitly silence sometimes.

Where both modes aren't inherently dangerous, i.e. they won't directly cause undefined states to execute.

--------------------

Concerning the nesting in my examples - I'm used to the style of C programming where failing is mostly handled by a return as to keep the program as readable (and thus flat) as possible. So pardon my french but I assumed "// do something" would somehow prevent further usage of 'f'.

Note that the Go example, although tedious, isn't bad in cases where you really do need to check every single possible error.

Re:Why I’m not leaving Python for Go by lmm on Monday September 24, 2012 @05:43AM (#4563893)
I find Java exceptions quite good for cases where you want to fail at a much coarser level than the specific problem, but finer than the whole program. E.g. my previous^2 job was essentially a message-processing system; it had a bunch of loops that took messages off queues and processed them one at a time. If processing any given message threw an (uncaught) exception, it marked that message for retry or as failed and carried on.

You could certainly argue for handling each message in a separate process a la erlang, but this approach worked well for us.

I think checked exceptions were a mistake (IIRC Gosling agrees), and Java could do with better support for multiple return values (which exceptions get abused for), but I like Java-style runtime exceptions.

Re:Why I’m not leaving Python for Go by masklinn on Monday September 24, 2012 @01:49PM (#4565962)
> You could certainly argue for handling each message in a separate process a la erlang, but this approach worked well for us.

I'm pretty sure you wouldn't do that. You'd have a shallow tree of processes, each leaf process would be tasked with doing message processing e.g. provided by its supervisor. The supervisor would "manage the queue" so to speak, and depending on the semantics of the queue it would have 1 to n children; and it would be tasked with marking failed messages when a child process would blow up (and restarting a new child).

Modelling messages as processes would likely be impractical.

Re:Why I’m not leaving Python for Go by pron on Monday September 24, 2012 @08:10AM (#4564198)
I think this is not what you're actually seeing. When you get an exception there is rarely much you can do other than log the error or alert the user. It is much more important what you do not do in such a case - you do not let bad data flow into your program, and exceptions are great at preventing that.
Re:Why I’m not leaving Python for Go by praptak on Monday September 24, 2012 @03:28AM (#4563595)
Ad your last Python example - the preferred method of doing resource cleanup in Python is the 'with' mechanism:

    with open("x.txt") as f:
        #do stuff with f
That's it. Obviously, compared to 'defer', it hides stuff - the actual magic happens in special methods __enter__ and __exit__ of the object passed to 'with'.
Re:Why I’m not leaving Python for Go by vidarh on Monday September 24, 2012 @07:10AM (#4564049)
Ruby by convention uses blocks for the same situation:

    def withSomeResource
        handle = acquireSomeResource
        yield handle
    ensure
        freeSomeResource(handle) if handle
    end
    
    withSomeResource do |h|
        h.whatever
    end
File.open and other parts of the standard library does that by default. I imagine the Python implementation of "with" is pretty similar, given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..":

    def with r
        r.__enter__
        yield(r)
    ensure
        r.__exit__
    end
Re:Why I’m not leaving Python for Go by praptak on Monday September 24, 2012 @07:35AM (#4564099)
The two mechanisms are not very similar. With the blocks mechanism (if I understand correctly) the resource itself implements a method "execute this code and clean up yourself". This only uses the standard mechanisms of the language (i.e. blocks.) The control is with the resource.

Python's 'with' inverts the control - the control is with the language runtime and the resource is passive here. In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime. The resource itself (or the contextmanager representing it) only implements __enter__ and __exit__ and is passive with regards to this mechanism.

Re:Why I’m not leaving Python for Go by vidarh on Monday September 24, 2012 @09:43AM (#4564593)
> With the blocks mechanism (if I understand correctly) the resource itself implements a method "execute this code and clean up yourself".

Where the method is doesn't matter, e.g. the (incomplete) example I gave of implementing "with" in Ruby that shows a method that can be defined in the global "main" scope or wherever you want.

Some classes implement class-methods to instantiate an object and pass it to a black and free the resource as a convenience, such as File.open, but it could go wherever else.

The resource itself most certainly does not need to know a thing about it as long as its API lets you do the cleanup you want/need.

> The control is with the resource.

The control is with whatever calls yield. Whether that be a method on the global "main" object (closest thing Ruby has to a global, freestanding function) or on the class of the resource itself, or an explicit "begin ... ensure ... end" block if you only need it once.

> In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime.

Which is why I gave my example of how I thought "with" would look like in Ruby (as it turns out I missed some exception handling in order for it to be equivalent to the Python version in functionality).

Re:Why I’m not leaving Python for Go by tsuraan on Monday September 24, 2012 @11:09AM (#4565030)
Which is why I gave my example of how I thought "with" would look like in Ruby (as it turns out I missed some exception handling in order for it to be equivalent to the Python version in functionality).

What you can't do, though, is express ruby's blocks using python's with statement; ruby is strictly more powerful here. One simple example of this is ruby's fork statement, which runs the code in the block in a process of its own:

    fork { puts "child" }
    puts "parent"
That will print "child" and "parent" once each, and it works because the fork method has control over the block's execution, so it can choose to only evaluate the block in the child's context. In python, the approximate code would be:

    with fork():
      print 'child'
    print 'parent'
However, python doesn't allow the resource to control block execution, so this code can't work (within standard python; there's a bytecode hack that can make it work, but that's outside the spec). Anyhow, I guess we've diverged pretty hard from the article, but I can never pass up the opportunity to vent against python's with statement.
Re:Why I’m not leaving Python for Go by masklinn on Monday September 24, 2012 @08:38AM (#4564308)
> given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..":

Note that there's a difference in the handling of exceptions: if an exception is triggered from the `with` block, it is intercepted, provided to __exit__ and can be silenced if needed or desired (by returning a truthy value). So a closer approximation would be:

    def with r
        r.__enter__
        begin
            yield(r)
        rescue Exception => e
            raise unless r.__exit__(e)
        else
            r.__exit__(nil)
        end
    end
Re:Why I’m not leaving Python for Go by vidarh on Monday September 24, 2012 @09:44AM (#4564595)
Ah. Wasn't aware of the ability to silence the Exceptions. Thanks.
Re:Why I’m not leaving Python for Go by masklinn on Monday September 24, 2012 @01:46PM (#4565943)
Yeah, I don't expect it would be very useful in Ruby, but it's not uncommon for Python (and its users) to use exceptions for flow control (see GeneratorExit and StopIteration)
Re:Why I’m not leaving Python for Go by masklinn on Monday September 24, 2012 @08:29AM (#4564270)
> Obviously, compared to 'defer', it hides stuff - the actual magic happens in special methods __enter__ and __exit__ of the object passed to 'with'.

Then again, `f.Close()` could hide any "magic" you want as well.

Re:Why I’m not leaving Python for Go by klon on Monday September 24, 2012 @03:49AM (#4563645)
Java 7 has AutoCloseables for resource cleanup:

  try (FileInputStream f = new FileInputStream(path)) {
      // do stuff
  }
Re:Why I’m not leaving Python for Go by draven on Monday September 24, 2012 @05:21AM (#4563854)
The python mechanism is more general, you can use the /with/ construct with locks for example.
Re:Why I’m not leaving Python for Go by andrewaylett on Monday September 24, 2012 @05:30AM (#4563869)
You can do the same with Java. Both are in a sense trying to re-gain the most useful parts of RAII semantics from C++: making it much more difficult to forget to clean up resources after you've finished with them.
Re:Why I’m not leaving Python for Go by draven on Monday September 24, 2012 @10:51AM (#4564939)
Or the unwind-protect faciliy from Common Lisp, that is "cleanup stuff before it goes out of scope"
Re:Why I’m not leaving Python for Go by dvhh on Monday September 24, 2012 @03:57AM (#4563665)
About fucking time
Re:Why I’m not leaving Python for Go by flyinRyan on Monday September 24, 2012 @07:37AM (#4564104)
>try: >> f = float(someText) >> catch ValueError: >> # I just parsed you, this is crazy, >> # here's an exception, throw it maybe?

No, you have it exactly backwards. It's with return values that you have to check after every call to be safe. With exceptions you can truly say: if I don't know what to do if this fails then I don't do anything. You can let the exception bubble up higher, all the way up to crashing the program if you like (which gives a nice stack trace that can then be debugged).

With return values, if you don't check then you could be building up more and more trash and you won't even know it until you either hit a point of code that finally does look at what's returned, or if an exception occurs (e.g. segfault).

Re:Why I’m not leaving Python for Go by Edootjuh on Monday September 24, 2012 @08:20AM (#4564234)

    try:
       f = float(someText)
    catch ValueError:
       # I just parsed you, this is crazy,
       # here's an exception, throw it maybe?
Formatted That For You
Re:Why I’m not leaving Python for Go by Evbn on Monday September 24, 2012 @11:17PM (#4568375)
"Not checking" is just shorthand for pythons " except: pass".
Re:Why I’m not leaving Python for Go by prodigal_erik on Monday September 24, 2012 @11:23PM (#4568393)
But not checking is invisible. I can't grep for it. It doesn't stand out in a code review. It's almost never what I meant to do, so it shouldn't have been the default or easily overlooked, much less both.
Re:Why I’m not leaving Python for Go by vog on Monday September 24, 2012 @03:27AM (#4563593)
Python doesn't have defer/panic, but it does have "with" statements which solve this issue in a RAII-like style:

    with open('foo') as f:
        # do stuff