facha
facha

Reputation: 12522

How to assign value to function parameter in python

I'd like to initialise a variable inside a function (so that the final print statement in my example outputs 10):

def init_param(param):
    param = 10

n = 1
init_param(n)
print n                   # prints 1

Is this doable in python?

Upvotes: 1

Views: 13015

Answers (4)

ravi
ravi

Reputation: 10733

Arguments are assigned inside the function as it's local variables. So all principles apply here.

  • Immutable objects cannot be changed.
  • Mutable objects can be modified in place.

You're intending to modify an immutable object, which is not possible. So your only options are :-

def init_param(param):
    param = 10
    return param

n = 1
n = init_param(n)
print n

which is pretty much useless OR

def init_param(param):
    param[0] = 10

n = [1]
init_param(n)
print n   

Upvotes: 4

praveen chaudhary
praveen chaudhary

Reputation: 95

def init_param(param):
    param = 10

n = 1
init_param(n)
print n 

here n is a integer (immutable data type) so it will be passed by value and so value of n will be unchanged.

lets take a mutable data type (ex. list) then it will be passed by referenced and so values in list will be changed.

def init_param(a):
    a[0] = 10

arr = [1] 
init_param(arr)
print(arr[0]) # print 10

so you have to check first whether the data is mutable or immutable.

otherwise you can use global keyword to access global variables.

def f():
    global n
    n = 10
n = 1
f()
print(n) # print 10

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Short answer: no, you can't.

Longer answer: in

def init_param(param):
    param = 10

the name param is local to the init_param function. Rebinding this name will change the value bound to the name param in the function's local scope, but will have absolutely no effect on the name n in the caller's scope - those names live in totally distinct namespaces. You can read Ned Batcheler's reference article on Python's names and binding for more in-depth explanations.

What would work would be to use a mutable container - a dict for example - and mutate this container, ie:

def init_param(params, name, value):
    params[name] = value

params = {
   "n": 1,
   "answer": 42,
   "parrot": "dead"
   }

init_params(params, "n", 10)
print(params)

(if you don't understand why this one works, re-read Ned Batcheler's article linked above)

Upvotes: 1

MaNKuR
MaNKuR

Reputation: 2704

First of all python function passes the value by object and the reference name here param is just a reference to a value hold by n.

Now coming to the solution, yes it could be possible provided you pass the variable name

def init_param(var_name):
    globals()[var_name] = 10

n = 1
init_param('n')
print n

Hope it will answer!

Upvotes: 1

Related Questions