user10870615
user10870615

Reputation:

'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?

Upvotes: 0

Views: 74

Answers (1)

Huw Thomas
Huw Thomas

Reputation: 317

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.

Upvotes: 2

Related Questions