Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a robot variable by reference to a python function

I use my own python function in Robot Framework. I give 3 parameters, these parameters are Robot Framework variables. When I modify the variables in my function, it is not modified in Robot Framework. So I deduce the variables are passed by value and not by reference... Is there a way to pass the variable by reference ? Or else to return the 3 variables as a result ?

Here is an example of Robot Framework code :

** Settings ***
 Library    OperatingSystem
 Library    myLib.MyLib    WITH NAME    MyLib

 Suite TearDown  teardown
 ** Variables **
 ${var}  azerty

 ** Test Cases **
 My test case
         log     ${var}
         myFunction    ${var}
         log     ${var}

With my python library :

import sys

 class MyLib(object):
     def __init__(self):
         return

     def myFunction(self,var):
         var="another value"

But as I said, the variable var remains "azerty" when I log it, and I would like the second log to print "another value" (as the function should change the value)

Thank for your help !

like image 897
François I Avatar asked Feb 11 '26 01:02

François I


1 Answers

All values are essentially passed by reference. If you change the value, you change it everywhere, but if you assign a different value to the variable, you're just making that variable point at a different value, not changing the original value.

For example:

def foo(d):
    d['bar'] = 'baz'
my_dict = {}
foo(my_dict)

Here, my_dict will be altered as a side effect of calling foo(my_dict).

However:

def foo(d):
    d = {'foo': 'bar'}
my_dict = {}
foo(my_dict)

Here, my_dict isn't changed. d is a local variable inside foo, and it's changed to point to a new dictionary instead of my_dict.

You also need to be aware that in python, you have mutable and immutable values. Strings, for example, are immutable. You'll never be able to change a string, you can only use a string to construct new strings (and often you'll assign these new values back to the same variable so it'll have a similar effect); having a side effect of a function be changing one of the values that's passed in can only work if they are mutable values.

It is generally a bad idea for your functions to change their arguments though. A better approach, is to have them return new values, which the caller can then do what they want with.

def myFunction(self, var):
    var = "another value" # I assume that another values is based somehow on the original
    return var

Alternatively, you could use attributes on your class:

class MyLib(object):
    def __init__(self):
        self.var = "initial value"
    def myFunction(self):
        self.var = "another value"
like image 118
SpoonMeiser Avatar answered Feb 13 '26 14:02

SpoonMeiser