M
M
mkone1122021-01-01 11:41:23
Python
mkone112, 2021-01-01 11:41:23

How to create an object that will unpack itself into the required number of names?

class Unpacker:
    ...
u = Unpacker()
a, b = u
print(a,b)  # 1, 2
a, b, c = u
print(a,b,c)  # 1, 2, 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-01-01
@mkone112

No way, too many values ​​for unpacking is also bad. And the object will not be able to find out the number of unpacked variables without code analysis.
Actually, the main question here again is "why do you need this?"
EDIT: Well don't say you weren't warned...

# оба модуля - встроенные, а не сторонние
import inspect
import dis

def callee(x):
    our_frame = inspect.currentframe()
    our_caller_frame = our_frame.f_back
    our_caller = our_caller_frame.f_code
    print(f"We are called by {our_caller.co_name}(), at line {our_caller_frame.f_lineno}")
    print("Our caller's code goes as following (byte string):")
    print(our_caller.co_code)
    bytecode = dis.Bytecode(our_caller, first_line=our_caller.co_firstlineno)
    print("Or, in human readable form, its this:")
    print(bytecode.dis())
    return [x*x]


def caller():
    print("Calling callee()")
    y = callee(2)
    print(y)

def other_caller():
    print("Calling callee()")
    z, *_ = callee(3)
    print(z)

caller()
other_caller()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question