0

I want to write a python program. My code looks like this

if __name__ == "__main__":
   a,b = ParseArgs() # this is my function which uses argparse lib
   n = 30
   x = np.random.randint(20)
   do_sth(a,b) # this function uses n and x inside its definition

I'm wondering if I could do sth like this:

def setup():
    a,b = ParseArgs() # this is my function which uses argparse lib
    n = 30
    x = np.random.randint(20)

if __name__ == "__main__":
   setup()
   do_sth(a,b) # this function uses n and x inside its definition

so that code looks more clear (note that in my real code setup part is much longer). I suppose that I can't do it, first of all because do_sth uses x and n. But what if I just change do_sth so that it takes x and n as arguments? Would it then be a good idea to put lines that create some global variables in setup function?

Brzoskwinia
  • 371
  • 2
  • 11
  • 2
    Please consider to use ``return x, n`` in ``setup()``. Then you can do: ``a, b = setup(); do_sth(a,b)`` - no need for global variables at all. (``;`` only used to write the code in one line, please don't do this in your app). Also: [Are global variables bad?](https://stackoverflow.com/questions/484635/are-global-variables-bad) – Mike Scotty Dec 09 '21 at 09:48
  • @MikeScotty thanks, 1.I like the idea of returning from setup 2.I'd been confused about global variables (I used to think they shouldn't be used at all, but then I saw some global vars in code in my job written by more experienced programmers) - but now thanks to answers to the question you linked I think I understand it finally :) – Brzoskwinia Dec 09 '21 at 15:20
  • 1
    Even more experienced programmers sometimes are just lazy - the bad lazy. As a rule of thumb: stick to your belief that global variables shouldn't be used at all. There are some very good exceptions to that rule - but they really are exceptions. When in doubt: dont use globals. – Lydia van Dyke Dec 09 '21 at 18:03

0 Answers0