0

I create a function dynamically this way:

def create_function(value):
    def _function():
        print value
return _function

f1 = create_func(1)
f1()

which works fine and prints '1'.

but my problem is slightly different, say there is a variable called no_of_arguments which contains the number of arguments the function that is being returned (_function() ) takes.

def create_function():
    no_of_arguments = int(raw_input()) #provided by user
    def _function(a,b,c,....): 

'this function has to accept a certain number of arguments, specified in the variable no_of_arguments'

        #do something here
return _function

f1 = create_func()
f1(a,b,c......)
2
  • 2
    Perhaps you should explain what you're really after... Commented Jul 2, 2013 at 7:23
  • 1
    I don't understand what you really want, but there are *args and **kwargs keywords for functions with arbitrary parameters in Python. May be they will be helpfull. Commented Jul 2, 2013 at 7:30

4 Answers 4

1

Use * in the function arguments to make it accept any number of positional arguments.

def func(*args):
    if len(args) == 1:
       print args[0]
    else:
       print args
...        
>>> func(1)
1
>>> func(1,2)
(1, 2)
>>> func(1,2,3,4)
(1, 2, 3, 4)
Sign up to request clarification or add additional context in comments.

Comments

0

A function can be defined as taking any (minimum) number of arguments by preceding one with a *, which will then result in the name being bound to a tuple containing the appropriate arguments.

def foo(a, b, *c):
  print a, b, c

foo(1, 2, 3, 4, 5)

You will need to limit/check the number of values passed this way yourself though.

Comments

0

You could use *args:

def create_function():
    no_of_arguments = int(raw_input()) #provided by user
    def _function(*args):
        if len(args) == no_of_arguments:
            dostuff()
        else:
            print "{} arguments were not given!".format(no_of_arguments)
    return _function

Running it as an example:

>>> f1 = create_function()
4 # The input
>>> f1('hi','hello','hai','cabbage')
>>> f1('hey')
4 arguments were not given!

Comments

0

As far as i understood, you need to pass different number of arguments to the function You can pass different number of arguments using * like that:

def create_function():
    no_of_arguments = (argList) #tuple of arguments
    def _function(*argList): 

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.