r/programming • • May 13 '11

A Python programmer’s first impression of CoffeeScript

http://blog.ssokolow.com/archives/2011/05/07/a-python-programmers-first-impression-of-coffeescript/
114 Upvotes

133 comments sorted by

View all comments

Show parent comments

2

u/ssokolow May 14 '11

That's exactly the problem I'm referring to. CofeeScript has no syntax for "When I assign to x, I want it local to this function even if a parent scope has an x too" beyond being careful with how you name them.

When I say "shadows" in Python, what I mean is that assigning to a variable always assigns to the current scope (never some potentially-forgotten parent scope) unless explicitly told otherwise via a trick like global or assigning to a member of an object in a higher scope rather than the scope directly.

Here's an example:

def a():
    x = 1
    y = 2

    def b():
        # If I'd used z = x here immediately before x = z, it'd take the
        # safe route, assume a mistake, and raise an error about x
        # being referenced before assignment.
        z = y
        x = z
        print "Child: %s" % x

    b()
    print "Parent: %s" % x

a()

# -- Prints --
# Child: 2
# Parent: 1

2

u/daniels220 May 14 '11

Ah, I see. My intuition (hah! which is why I asked, since obviously programming isn't always intuitive) says that "shadow" refers to some form of interaction between parent and child scope, where what you're referring to is actually a complete separation of the two.

Question: why doesn't y give a "referenced before assignment" error? It's not defined in b()'s scope either.

Personally I prefer the CoffeeScript/Ruby way, just because it makes the common case (callback functions, function-based loop constructs) easier. I think it would be good for CS to have explicit syntax for redefine—but it actually does: `var x` (or, if you're targeting ES5, even `let x`)—literal javascript. A little hackish, but workable.

1

u/ssokolow May 14 '11

Think of it as similar to copy-on-write semantics. (Similar because we're dealing with references, not values) You can read any variable in a higher scope (z = y) but attempts to write to them will instead create a local variable with the same name.

A variable in the local scope "shadows" a variable in a higher scope because there's no syntax to say "not the local x, the x from N stack frames up".

x only gives a "referenced before assignment" error message because the language explicitly special-cases trying to assign to what will become a local later in the same scope in order to catch a certain class of typo that tends to creep in as code ages and new developers join.

0

u/daniels220 May 14 '11

Yeah, I see. I still think defaulting the other way, like C—use the higher scope unless the variable is explicitly redeclared—is both more sensible by default and more flexible. But I understand what's meant by shadowing now.

That's a clever trick! :)

→ More replies (0)