N
N
Nicholas V2018-02-08 11:50:40
Python
Nicholas V, 2018-02-08 11:50:40

How to force default values ​​of function arguments to be calculated each time?

How to make the default values ​​of the arguments calculated on each function call?

from random import randint, uniform

def my_func(  arg_1 = uniform( 0.8, 2.2 ), 
              arg_2 = randint( -3, 3 ),
              arg_3 = randint( -3, 3 ) ):
    print( arg_1 )    
    print( arg_2 )
    print( arg_3 )

my_func()
my_func()
my_func()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nicholas V, 2018-02-08
@Amunrah

Thanks everyone for the tips. The result is this solution:
Input:

from random import uniform, randint

def reload_defaults( func ):
    def reloader( *args, **kwargs ):
        defaults = [ ('arg_1', uniform( 0.8, 2.2 ) ), ('arg_2', randint( -3, 3 )),  ('arg_3', randint( -3, 3 )) ]
        args = { val[0]:args[i] if len(args) > i else val[1] for i,val in enumerate(defaults) }
        args.update( kwargs )
        return func( **args )
    return reloader

@reload_defaults
def my_func(  arg_1, arg_2, arg_3 ):
    print( arg_1 )    
    print( arg_2 )
    print( arg_3, '\n' )
    
my_func()
my_func( 1, arg_3 = 45 )
my_func( arg_2 = 145 )
my_func( uniform(10.5, 20.5) )
my_func( 33, 10 )
my_func( 5, 7, randint(-10, 10 ) )

Conclusion:
1.9722310572222892
0
3 

1
-1
45 

0.890632243066556
145
3 

12.374446906130364
1
-3 

33
10
-3 

5
7
-7

The decorator is convenient because it can be hidden in another module.

L
lega, 2018-02-08
@lega

No, the values ​​are created at the time of compilation of the function (although you can compile dynamic each time).
But they usually do it like this:

def foo(value=None):
  value = value or []

S
Stanislav Pugachev, 2018-02-08
@Stqs

something like this

from random import randint, uniform

def argrandomizer(func):
    def wrapper():
        arg_1 = uniform(0.8, 2.2)
        arg_2 = randint(-3, 3)
        arg_3 = randint(-3, 3)
        return func(arg_1, arg_2, arg_3)
    return wrapper

@argrandomizer
def my_func(arg_1, arg_2, arg_3):
    print( arg_1 )    
    print( arg_2 )
    print( arg_3 )

my_func()
my_func()
my_func()

conclusion
1.48763356514
-3
-3
2.07023550873
-2
3
1.48356419425
-2
-1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question