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.

David Dahan
  • 10,576
  • 11
  • 64
  • 137

2 Answers2

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.

Community
  • 1
  • 1
user2357112
  • 260,549
  • 28
  • 431
  • 505
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)
Ranaivo
  • 1,578
  • 12
  • 6