0

I have a function that returns two values:

def dbfunc:
  # ...
  return var1, var2

I have this class:

class MyClass:
  foo = ...
  bar = ...

I'd like to assign the result of dbfunc() to the MyClass instance I'm trying to create. I'd tried this:

my_object = MyClass(dbfunc()) # does not work because the return type is a tuple

I could do this:

res = dbfunc()
my_object = MyClass(foo=res[0], bar=res[1])

but I'm actually trying to do this in a middle of a comprehensive list so I can not make these kind of "pre-affectations". I have to do it in one time.

Thanks for help.

2 Answers 2

3

Argument unpacking:

my_object = MyClass(*dbfunc())

Put a * before the last argument to a function, and Python will iterate over that argument and pass the elements to the function as separate positional arguments. You can use ** with a dict for keyword arguments.

Also, it looks like you may have a bug regarding class vs. instance attributes. See "How do I avoid having Python class data shared among instances?". It might or might not be fine, depending on the parts of MyClass you stripped out.

Sign up to request clarification or add additional context in comments.

Comments

0

You can define more simply your function and your class I think as shown below.

def dbfunc:
    # ...
    return var1, var2

class MyClass:
    def __init__(foo, bar):
        self.foo = name
        self.bar = bar

[var1, var2] = dbfunc()
my_object = MyClass(var1, var2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.