python - Find out into how many values a return value will be unpacked -
i have function, , when called, i'd know return value going assigned - when unpacked tuple. so:
a = func() # n = 1 vs.
a, b, c = func() # n = 3 i want use value of n in func. there must magic inspect or _getframe lets me this. ideas?
disclaimer (because seems neccessary nowadays): know funky, , bad practice, , shouldn't used in production code. looks i'd expect in perl. i'm not looking different way solve supposed "actual" problem, i'm curious how achive asked above. 1 cool usage of trick be:
one, two, 3 = count() one, two, three, 4 = count() with
def count(): n = get_return_count() if not n: return return range(n)
adapted http://code.activestate.com/recipes/284742-finding-out-the-number-of-values-the-caller-is-exp/:
import inspect import dis def expecting(offset=0): """return how many values caller expecting""" f = inspect.currentframe().f_back.f_back = f.f_lasti + offset bytecode = f.f_code.co_code instruction = ord(bytecode[i]) if instruction == dis.opmap['unpack_sequence']: return ord(bytecode[i + 1]) elif instruction == dis.opmap['pop_top']: return 0 else: return 1 def count(): # offset = 3 bytecodes call op unpack op return range(expecting(offset=3)) or object can detect when unpacked:
class count(object): def __iter__(self): # offset = 0 because @ unpack op return iter(range(expecting(offset=0)))
Comments
Post a Comment