1

Inspired by this Q, and my current task.

Let's take a look to small example:

#!/usr/bin/env python

def one():
    global x
    x = 'Global var'
    print(x)

def two():
    print(x)

one()
two()

OK, global is bad. What solution? Use arguments? Like this:

#!/usr/bin/env python

def one():
#    global x
    x = 'Non global var'
#    print(x)
    return(x)

def two(x):
    print(x)

one()
two(one())

But - what if I have set of vars, necessary in few other functions? For example - 20 vars. Pass every as single object? Return some kind of list? Like this:

def one():
#    global x
    x = 'Non global var'
    a, b, c = 'a', 'b', 'c'
    list = [a, b, c, x]
#    print(x)
    return(list)

def two(x):
    print(x)

one()
two(one())

Or use classes inheritance? Like this:

#!/usr/bin/env python

class First:
    def __init__(self):
        self.x = 'Non global var'
        self.a, self.b, self.c = 'a', 'b', 'c'

class Second(First):
    def two(self):
        o = First()
        print(o.x, o.a, o.b, o.c)

a = First()
b = Second()

b.two()

So - question is - Why globals are bad? and - what to do, if you have lot of vars, used in much parts of programm?

Community
  • 1
  • 1
setevoy
  • 4,374
  • 11
  • 50
  • 87

0 Answers0