Write a few lines of Python code, X, that does not reference any global variables, such that
def method():
X
print(a)
method()
prints 1 but
def method():
X
X
print(a)
method()
prints 2.
So, I hate to be a stickler, but it seems like vars and locals are actually global variables in Python:
def test_global_1():
global vars, locals
vars = lambda: 2
locals = lambda: 3
def test_global_2():
print(vars())
print(locals())
test_global_1()
test_global_2()
Also, it looks like people would like to see objective winning criteria for puzzles like this. Code length doesn't really feel right here so perhaps we could make a system of brownie points for various novel features of the code? I'm not sure exactly what these could be but here's a start:
- +1 for really truly no globals (no
varsorlocals) - +1 for being the first to post a particular technique
- +1 for the shortest solution posted
- +1 for a solution involving only a single Python statement
- +1 for interesting "hacks" like joining at lexical non-boundaries
- +1 for not using exceptions
And if you can think of more you could edit this question to add to the list.
Can this problem be solved without using exceptions and without using globals like vars and locals? I suspect it can, though I haven't figured out exactly how yet...
X, but there are other options. \$\endgroup\$