Search code examples
pythoncontextmanager

'With' statement with throwaway variables?


Is it possible to do something like the following in python?

def func():
    with "Bill" as name:
        print(name)
    # ... more stuff below ...

I know it could be done with a function/closure like:

def func(): 
    def _with(name):
        print(name)
    _with(name="Bill")
    # ... more stuff below ...

But is there another way to do this (without doing a lot of heavy lifting by subclassing the string and doing enter/exit methods?


Solution

  • def func():
        name = 'Bill'
        print(name)
    

    The variable name is thrown away after the function call ends since it is only local to func.

    NB the colon after the func definition.