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>There is no problem with <strong>accessing</strong> global variables from functions (including lambdas), without using <code>global</code>:</p>

<pre><code>&gt;&gt;&gt; a = 1
&gt;&gt;&gt; b = list()
&gt;&gt;&gt;
&gt;&gt;&gt; def f():
...     b.append(a)
...
&gt;&gt;&gt; f()
&gt;&gt;&gt; print(b)
[1]
</code></pre>

<p>As you can see above, a global variable can be read and the object in the variable can be used without any restrictions.</p>

<p>What can not be done without a <code>global</code> is <strong>assigning</strong> an object to a global variable. That is because an assignment automatically creates a local variable.</p>

<pre><code>def f():
    a = 4  # this is a new local variable a, regardless of whether there is a global 'a'
</code></pre>

<p>Hence, the following is fine:</p>

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

<p>On the other hand, if you really wanted to assign value to a global variable, that would be impossible within a lambda (other than by hacks, such as accessing the globals directory...)</p>

python