简体   繁体   中英

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM