Skip to content

Instantly share code, notes, and snippets.

@matthewryanscott
Created December 9, 2009 04:51
Show Gist options
  • Save matthewryanscott/252271 to your computer and use it in GitHub Desktop.
Save matthewryanscott/252271 to your computer and use it in GitHub Desktop.
# The general idea is to attach a sequence to an object upon instantiation.
# When creating kwargs to pass to dict(), Python evaluates each expression
# in the order written, and thus each Field instance in this example has
# a _number attribute that corresponds to the order in which it was written
# in source code.
class Field(object):
_last_number = 0
def __init__(self, **kw):
self.__dict__.update(kw)
self._number = Field._last_number + 1
Field._last_number += 1
bag_o_fields = dict(
foo=Field(a=1),
bar=Field(x=9),
abc=Field(q=5),
)
def item_number(item):
return item[1]._number
for field_name, field in sorted(bag_o_fields.items(), key=item_number):
print field_name, field.__dict__
# Output:
# foo {'a': 1, '_number': 1}
# bar {'x': 9, '_number': 2}
# abc {'q': 5, '_number': 3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment