call by reference in python

By: Python Documentation Team Emailed: 1730 times Printed: 2344 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.

 

  1. By returning a tuple of the results:

    def func2(a, b):
        a = 'new-value'        # a and b are local names
        b = b + 1              # assigned to new objects
        return a, b            # return new values

    x, y = 'old-value', 99
    x, y = func2(x, y)
    print(x, y)                # output: new-value 100

    This is almost always the clearest solution.
  2. By using global variables. This isn’t thread-safe, and is not recommended.
  3. By passing a mutable (changeable in-place) object:

    def func1(a):
        a[0] = 'new-value'     # 'a' references a mutable list
        a[1] = a[1] + 1        # changes a shared object

    args = ['old-value', 99]
    func1(args)
    print(args[0], args[1])    # output: new-value 100
  4. By passing in a dictionary that gets mutated:

    def func3(args):
        args['a'] = 'new-value'     # args is a mutable dictionary
        args['b'] = args['b'] + 1   # change it in-place

    args = {'a':' old-value', 'b': 99}
    func3(args)
    print(args['a'], args['b'])
  5. Or bundle up values in a class instance:

    class callByRef:
        def __init__(self, **args):
            for (key, value) in args.items():
                setattr(self, key, value)

    def func4(args):
        args.a = 'new-value'        # args is a mutable callByRef
        args.b = args.b + 1         # change object in-place

    args = callByRef(a='old-value', b=99)
    func4(args)
    print(args.a, args.b)


There’s almost never a good reason to get this complicated.

Your best choice is to return a tuple containing the multiple results.


Python Home | All Python Tutorials | Latest Python Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Python Documentation Team
with in Python
goto in Python
Garbage Collection in Python
switch case statement in Python
Overloading in python
Static in python
Delegation in python
Schwartzian Transform in python
Multidimensional list (array) in python
Array in python
Remove duplicates from a list in python
Iterate over a sequence in reverse order in python
Convert between tuples and lists in python
Perl's chomp() equivalent for removing trailing newlines from strings in python
Convert number to string in python

More Tutorials in Python
What is the need for Python language?
How to compile python script and create .pyc file?
How to find the current module name in python
How to force rereading of a changed module in python
UnboundLocalError in python
call by reference in python
Callable objects in python
Ternary operator in python
Hexadecimal and Octal integers in python
Convert string to number in python
Convert number to string in python
Perl's chomp() equivalent for removing trailing newlines from strings in python
Convert between tuples and lists in python
Iterate over a sequence in reverse order in python
Remove duplicates from a list in python

More Latest News
Most Viewed Articles (in Python )
Formatted printing in Python
How to compile python script and create .pyc file?
Callable objects in python
Unknown command: 'migrate'
How to find the current module name in python
Installing gedit for python programming in Windows
Convert number to string in python
Schwartzian Transform in python
goto in Python
UnboundLocalError in python
call by reference in python
Convert string to number in python
Convert between tuples and lists in python
Remove duplicates from a list in python
Multidimensional list (array) in python
Most Emailed Articles (in Python)
How to find the current module name in python
Perl's chomp() equivalent for removing trailing newlines from strings in python
Comments And Pound Characters in Python
Numbers And Math in Python
Printing in Python
How to compile python script and create .pyc file?
Callable objects in python
Hexadecimal and Octal integers in python
Installing gedit for python programming in Windows
Installing gedit for python programming in Linux
Your First Program in Python
Variables And Names in Python
Variables And Printing in Python
Strings And Text in Python
Formatted printing in Python