Skip to content

Instantly share code, notes, and snippets.

@solex
Created October 28, 2010 09:41
Show Gist options
  • Save solex/651021 to your computer and use it in GitHub Desktop.
Save solex/651021 to your computer and use it in GitHub Desktop.
Populates all classes with "altitude", measured as the number of lines from the bottom of the file. And the very useful "fly" function
import inspect
class GravitationalError(Exception):
pass
class Fly(object):
def __get__(self, instance=None, owner=None):
def fly(*args, **kwargs):
alt_str = "Flying at the height of %d lines. " % owner.altitude
members = inspect.getmodule(owner).__dict__.values()
lst = [(m, m.altitude) for m in members if inspect.isclass(m)]
pos_str = "All alone here"
if len(lst) > 1:
ordered = [x[0] for x in sorted(lst,key=lambda x: x[1])]
pos = ordered.index(owner)
if pos == 0:
pos_str = 'At the very bottom, below the "%s"' % \
ordered[pos+1].__name__
elif pos == len(ordered)-1:
pos_str = 'At the very top, above the "%s"' % \
ordered[pos-1].__name__
else:
pos_str = 'Between "%s" and "%s"' %\
(ordered[pos-1].__name__, ordered[pos+1].__name__)
return alt_str + pos_str + ". It's all Python! (http://xkcd.com/353/)"
return fly
class Altitude(object):
def __get__(self, instance=None, owner=None):
height = len(inspect.getsourcelines(inspect.getmodule(owner))[0])
return height - inspect.getsourcelines(owner)[1]
def __set__(self, instance, value):
raise GravitationalError("This is not how you're supposed to fly")
def levitate_all():
frame_globals = inspect.currentframe().f_back.f_back.f_globals
for cls in [val for val in frame_globals.values() if inspect.isclass(val)]:
cls.fly = Fly()
cls.altitude = Altitude()
levitate_all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment