In Perl, it\'s often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is \'undef\'. For instance:
my $x
I am quite convinced that there is no 'pythonic' way to do this, because this is not a pattern that is pythonic. Control should not reach an undefined variable reference in elegant code. There are similar ideas that are pythonic. Most obvious:
def myRange(start, stop=None):
start, stop = (0, start) if stop is None else (start, stop)
...
What's important is that stop
is defined in scope, but the caller didn't have to pass it explicitly, only that it has taken it's default value, altering the semantics of the arguments, which in effect causes the first argument to be optional instead of the second, even where the language does not allow that without this clever trick.
That being said, something like this might follow the premise without using a try-catch block.
a = locals().get('x', y)
If it's an argument to a function you can do this:
def MyFunc( a=2 ):
print "a is %d"%a
>>> MyFunc()
...a is 2
>>> MyFunc(5)
...a is 5
[Edit] For the downvoters.. the if/else bit is unnecessary for the solution - just added to make the results clear. Edited it to remove the if statement if that makes it clearer?
I think this would help, since the problem comes down to check whether a variable is defined or not:
Easy way to check that variable is defined in python?