0

I'm receiving JSON objects of arbitrary shape. And reform them into Lists mapped using __code__.co_varnames[:argc] Ending up with a List looking like this ["param1=hello", "param2=world"] in any order. Now I want to link them to the specific parameters in the function as below. But can't find how. In bash we have eval() I read something about using exec() but don't know how that should work.

def foo(param1:str, param2:str, *args) -> str:
    return param1 + param2

list1 = ["param1=hello", "param2=world" ]
list2 = ["param2=world", "param1=hello" ]

# Want to do something like this for both lists
print(foo(*list1))
print(foo(*list2))
1
  • 1
    What exactly are you trying to accomplish? None of what you describe should require messing with __code__ or eval. Can you post an example of your JSON and your intended output? Commented Mar 11, 2021 at 16:55

1 Answer 1

2

You can pass the function a kwargs dict of the form {"param1": "hello", "param2": "world"}. To achieve this, simply split() the strings with =:

kwargs = dict(s.split('=') for s in list1)
print(kwargs, foo(**kwargs))

Will give

{'param1': 'hello', 'param2': 'world'} helloworld
Sign up to request clarification or add additional context in comments.

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.