0

I have function which has 10 argument but each time i call a function i dont need to pass all the 10 arguments as all the 10 arguments are not relevant each time the function is called.

def function(arg1:Optional[int] =0,arg2:Optional[int] =0,arg3:Optional[int] =0,
            arg4:Optional[int] =0,arg5:Optional[int] =0, arg6:Optional[str] =None, 
            arg7:Optional[str] =None,arg8:Optional[str]=None,arg9:Optional[str]=None,arg10:Optional[str] =None)

    pass

How to convert these arguments into a class and pass that class in the function as an argument each time the function needs to be called so that only relevant arguments get passed each time the function is called?

If any one can give some hints pls.

4
  • 1
    Since all the arguments are optional, just pass them by name. function(arg2 = 10, arg7 = "foo") Commented Sep 21, 2022 at 17:04
  • Creating a class isn't actually going to help with any of this. Commented Sep 21, 2022 at 17:04
  • If you need to pass them dynamically, use a dictionary, then use function(**d) Commented Sep 21, 2022 at 17:05
  • The function as of now looks clumsy so need to clean it a bit by seperating arguments into a class. Commented Sep 21, 2022 at 17:06

1 Answer 1

1

Here's how you might bundle all of those argument values into a dataclass:

from dataclasses import dataclass
from typing import Optional

@dataclass
class FunctionArgs:
    arg1: Optional[int] = 0
    arg2: Optional[int] = 0
    arg3: Optional[int] = 0
    arg4: Optional[int] = 0
    arg5: Optional[int] = 0
    arg6: Optional[str] = None
    arg7: Optional[str] = None
    arg8: Optional[str] = None
    arg9: Optional[str] = None
    arg10: Optional[str] = None
    

def function(args: FunctionArgs) -> None:
    pass

You'd then call the function like this:

function(FunctionArgs(arg4=10))
Sign up to request clarification or add additional context in comments.

2 Comments

Even if we pass only arg4, the function returns other optional arguments as well. Is there a way to return only the arguments which are passed i.e. in the case above it should have only arg4
That question doesn't make sense. What function are you talking about?

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.