Tuesday, 15 May 2012

python - Using an OrderedDict in **kwargs -



python - Using an OrderedDict in **kwargs -

is possible pass ordereddict instance function uses **kwargs syntax , retain ordering?

what i'd :

def i_crave_order(**kwargs): k, v in kwargs.items(): print k, v illustration = ordereddict([('first', 1), ('second', 2), ('third', -1)]) i_crave_order(**example) >> first 1 >> sec 2 >> 3rd -1

however actual result is:

>> sec 2 >> 3rd -1 >> first 1

ie, typical random dict ordering.

i have other uses setting explicitly good, want maintain **kwargs , not pass ordereddict regular argument

no, not possible. or, rather, possible, ordereddict going turned dict anyway.

the first thing realize value pass in **example not automatically become value in **kwargs. consider case, kwargs have part of example:

def f(a, **kwargs): pass illustration = {'a': 1, 'b': 2} f(**example)

or case, have more values in example:

example = {'b': 2} f(a=1, c=3, **example)

or no overlap @ all:

example = {'a': 1} f(b=2, **example)

so, you're asking doesn't create sense.

still, might nice if there way specify want ordered **kwargs, no matter where keywords came from—explicit keyword args in order appear, followed of items of **example in order appear in example (which arbitrary if example dict, meaningful if ordereddict).

defining fiddly details, , keeping performance acceptable, turns out harder sounds. see pep 468, , linked threads, give-and-take on idea. seems have stalled time around, if picks , champions (and writes reference implementation people play with—which depends on ordereddict accessible c api, there in 3.5+), suspect language.

by way, note if were possible, used in constructor ordereddict itself. if seek that, you're doing freezing arbitrary order permanent order:

>>> d = ordereddict(a=1, b=2, c=3) ordereddict([('a', 1), ('c', 3), ('b', 2)])

meanwhile, options have?

well, obvious alternative pass example normal argument instead of unpacking it:

def f(example): pass illustration = ordereddict([('a', 1), ('b', 2)]) f(example)

or, of course, can utilize *args , pass items tuples, that's uglier.

there might other workarounds in threads linked pep, really, none of them going improve this. (except… iirc, li haoyi came solution based on macropy pass order-retaining keyword arguments, don't remember details. macropy solutions in general awesome if you're willing utilize macropy , write code doesn't quite read python, isn't appropriate…)

python kwargs

No comments:

Post a Comment