These are chat archives for LCAS/Human-Aware-Navigation

23rd
Mar 2016
Marc Hanheide
@marc-hanheide
Mar 23 2016 08:24
strongly suggesting making a class! Remember OOP!
class Something:
    def something(self, msg):
           self.varx = msg.pose.pose.position.x

    def somthingElse(self, data):
           #do stuff with data
           print self.varx
Christian Dondrup
@cdondrup
Mar 23 2016 09:18
I agree with @marc-hanheide global variables are an easy solution but very hard to read and understand.
Marc Hanheide
@marc-hanheide
Mar 23 2016 09:32
They are bad practice (in 99.9% of all cases)
Christian Dondrup
@cdondrup
Mar 23 2016 09:47

Just a quick explanation why your code didn't work:

def my_func():
     result = 0
     def my_print():
        print result
     my_print()

will, when executed, do this:

my_func()
> 0

This works because when reading from variables, python first looks in the local scope of the my_print function and does not find the variable result, therefore, it goes to the outer scope and finds result in my_func. If it wouldn't be in there, it would look for gloabally defined variables.

Assignment of variables, however, works differently:

def my_func():
     result = 0
     def set_result(data):
         result = data
     def my_print():
         print result

     set_result(5)
     my_print()

Now you'd expect that result will be 5 when my_print is executed. But running my_func results in

my_func()
> 0

This is because variable assignment always works on a local scope. That means thet in set_result python creates a new variable result that has nothing to do with the result of the outer scope. This behaviour is necessary because otherwise you could variable names only once in your code regardles of if they are in a function or not.