Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active June 7, 2017 06:37
Show Gist options
  • Save louisswarren/a76a04cfbad38be7db26de5dacb2482f to your computer and use it in GitHub Desktop.
Save louisswarren/a76a04cfbad38be7db26de5dacb2482f to your computer and use it in GitHub Desktop.
Use with blocks in python to assign a shorter name to a variable
class mutate(Exception):
pass
class alias:
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is mutate:
alias.mutate(self.obj, exc_value.args[0])
return True
@staticmethod
def mutate(obj, newobj):
if hasattr(obj, '__dict__'):
obj.__dict__ = newobj.__dict__
else:
obj.__init__(newobj)
# Testing
this_is_quite_a_long_name = [1, 2, 3]
with alias(this_is_quite_a_long_name) as foo:
assert(foo == [1, 2, 3])
assert(foo.pop() == 3)
assert(this_is_quite_a_long_name == [1, 2])
assert(foo == [1, 2])
assert(this_is_quite_a_long_name == [1, 2])
immutable_value = 'Hello, world!'
with alias(immutable_value) as bar:
assert(bar == 'Hello, world!')
bar = bar.replace('world', 'Steve')
assert(bar == 'Hello, Steve!')
assert(immutable_value == 'Hello, world!')
this_set_gets_changed_by_assignment = {1, 2, 4, 8, 16}
with alias(this_set_gets_changed_by_assignment) as baz:
baz = {3, 6, 9}
raise mutate(baz)
assert(this_set_gets_changed_by_assignment == {3, 6, 9})
# Immutable values will NOT be modified, however
hello = 'hello'
with alias(hello) as x:
x = 'goodbye'
raise mutate(x)
assert(hello == 'hello')
# Weird's constructor doesn't support a single Weird object as an argument.
# However, it is not a builtin, so it supports __dict__.
class Weird:
def __init__(self, height, color):
self.height = height
self.color = color
def __str__(self):
return 'My height is {}, and I am {}'.format(self.height, self.color)
weird_instance = Weird(42, 'blue')
with alias(weird_instance) as w:
w = Weird(10, 'red')
raise mutate(w)
assert(str(weird_instance) == 'My height is 10, and I am red')
# Examples
list_with_long_name = ['apples', 'pears']
with alias(list_with_long_name) as x:
print(x.count('apples'))
x = ['chickens', 'cows']
# Mutate is necessary because x was modified by assignment
raise mutate(x)
set_with_long_name = {1, 4, 9, 16, 25}
with alias(set_with_long_name) as foo:
print(foo & {1, 2, 3, 4, 5})
foo.intersection_update(range(7,22))
@louisswarren
Copy link
Author

louisswarren commented May 7, 2016

Of course, this is terrible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment