1

i have a class definition as follows :

class Trade:
  def __init__(self, **kwargs):
    # lots of things

I am trying to instantiate one by doing :

trade_tmp = Trade(json.loads(trade_str))

My understanding was that the **kwargs argument would automatically pickup the generated dictionary. Am I incorrect ?

I am getting the whole takes 1 positional argument but 2 were given error which I though should not apply here.

9
  • You actually need *args here not **kwargs. And just as an aside, "args" and "kwargs" are arbitrary - it's the asterisks that count. Commented Mar 7, 2019 at 1:43
  • and *args can be a dictionary as well ? I thought dict = **, not dict = * Commented Mar 7, 2019 at 1:45
  • Ah! I see.. so what you actually wanted to do is Trade(**json.loads(trade_str)) so that it would unpack your kwargs. Right? Commented Mar 7, 2019 at 1:48
  • No I ended up following your fist advice which I think was the correct one i.e pass a dict as a simple argument instead of passing named arguments. Commented Mar 7, 2019 at 1:51
  • if you want to post an answer i'll validate it since you were first on the case Commented Mar 7, 2019 at 1:51

2 Answers 2

1

The dict returned by json.loads serves as a single argument to the function. Therefore you need another positional argument:

def __init__(self, data, **kwargs)

While you could prepend two starts before the dict to force it as keyword arguments, it's not designed for this purpose and I recommend against this:

# it's valid, but don't do this
Trade(**json.loads(trade_str))
Sign up to request clarification or add additional context in comments.

Comments

0

Two choices, using args or kwargs:

import json

class Trade1:
  def __init__(self, **kwargs):
      print(kwargs)

class Trade2:
  def __init__(self, *args):
      print(args)

trade_str = '{"a": 1, "b": 2}'
trade_tmp1 = Trade1(**json.loads(trade_str))
trade_tmp2 = Trade2(json.loads(trade_str))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.