Apr-09-2020, 07:13 AM
I have shortened my function and code to make it easier to follow but it reflects an equivalent situation.
I am wondering when you define a function with input arguments having default values that are described as equations, where are the variables in the equations taken from my python? I shall explain with my example below.
I want the default value for y in the nested dictionaries to increase the more keys are added to the main dictionary as shown by y in the code below.
The output of the code is as follows:
Before: 100
Internal: 100
My_dict["1"]["y_position"]: 100
After 1: 110
Internal: 110
My_dict["2"]["y_position"]: 100
After 2: 120
So as you can see when the create function is run, the len(my_dict) is calculated using the original length of my_dict above the defined function rather than the new length of my_dict. Inside the function it uses the new my_dict value but in the argument defaults it seems to use the my_dict from above the function.
Am I correct? Is there any way to fix this so the argument uses the current variables when it is called?
Thank you so much in advance for this head sore, really appreciate any help with this.
I am wondering when you define a function with input arguments having default values that are described as equations, where are the variables in the equations taken from my python? I shall explain with my example below.
I want the default value for y in the nested dictionaries to increase the more keys are added to the main dictionary as shown by y in the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
my_dict = dict () default_sizes = [ 300 , 100 ] def create(text = "Default Text" , x = default_sizes[ 0 ], y = default_sizes[ 1 ] + ( 10 * len (my_dict))): local_dict = dict () local_dict[ "x_position" ] = x local_dict[ "y_position" ] = y print ( "Internal: " , default_sizes[ 1 ] + ( 10 * len (my_dict))) return local_dict print ( "Before: " , default_sizes[ 1 ] + ( 10 * len (my_dict))) my_dict[ "1" ] = create() print ( "My_dict[\"1\"][\"y_position\"]: " , my_dict[ "1" ][ "y_position" ]) print ( "After 1: " , default_sizes[ 1 ] + ( 10 * len (my_dict))) my_dict[ "2" ] = create() print ( "My_dict[\"2\"][\"y_position\"]: " , my_dict[ "2" ][ "y_position" ]) print ( "After 2: " , default_sizes[ 1 ] + ( 10 * len (my_dict))) |
Before: 100
Internal: 100
My_dict["1"]["y_position"]: 100
After 1: 110
Internal: 110
My_dict["2"]["y_position"]: 100
After 2: 120
So as you can see when the create function is run, the len(my_dict) is calculated using the original length of my_dict above the defined function rather than the new length of my_dict. Inside the function it uses the new my_dict value but in the argument defaults it seems to use the my_dict from above the function.
Am I correct? Is there any way to fix this so the argument uses the current variables when it is called?
Thank you so much in advance for this head sore, really appreciate any help with this.