Baz
Baz

Reputation: 13133

Accessing global from within lambda

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:

ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))

How should I be doing this?

Upvotes: 0

Views: 1011

Answers (2)

AChampion
AChampion

Reputation: 30258

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:

def func():
    ws = WebSocket(url)
    sch.on_receive(lambda msg: ws.send(msg))

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

def wrapper(url):
    ws = WebSocket(url)
    def send(msg):
        return ws.send(msg)
    return send

sch.on_receive(wrapper(url))

Or more tersely:

wrapper = lambda url: Websocket(url).send
sch.on_receive(wrapper(url))

But this is really just the equivalent of:

sch.on_recieve(WebSocket(url).send)

Upvotes: 0

zvone
zvone

Reputation: 19352

There is no problem with accessing global variables from functions (including lambdas), without using global:

>>> a = 1
>>> b = list()
>>>
>>> def f():
...     b.append(a)
...
>>> f()
>>> print(b)
[1]

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

What can not be done without a global is assigning an object to a global variable. That is because an assignment automatically creates a local variable.

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

Hence, the following is fine:

ws = WebSocket(url)
sch.on_receive(lambda msg: ws.send(msg))

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...)

Upvotes: 1

Related Questions