Accessing global from within lambda
<p>I never access globals from within functions, instead I pass them in as arguments. Therefore the following code feels weird to me, where I am accessing a global object directly from within the function:   </p>

<pre><code>ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))
</code></pre>

<p>How should I be doing this?</p>

<p>What's wrong with what you've written? It's not necessarily accessing the global scope, it's really accessing the local scope (and if it doesn't find the variable uses the global scope). Just as an example this is perfectly fine:</p>

<pre><code>def func():
    ws = WebSocket(url)
    sch.on_receive(lambda msg: ws.send(msg))
</code></pre>

<p>Because of this I think of it more as a closure than accessing globals. If you didn't do this with a <code>lambda</code> here's how you could do it:</p>

<pre><code>def wrapper(url):
    ws = WebSocket(url)
    def send(msg):
        return ws.send(msg)
    return send

sch.on_receive(wrapper(url))
</code></pre>

<p>Or more tersely:</p>

<pre><code>wrapper = lambda url: Websocket(url).send
sch.on_receive(wrapper(url))
</code></pre>

<p>But this is really just the equivalent of:</p>

<pre><code>sch.on_recieve(WebSocket(url).send)
</code></pre>

python