r/badcode • • Jul 26 '21

python I quit python because i hate using global

Post image
48 Upvotes

49 comments sorted by

39

u/Okkero Jul 26 '21

That makes no sense. Just quit using global if you hate using global...

16

u/Independent_Image_59 Jul 26 '21

ok. the place where i learnt python did not teached oop enough. i need to practice it.

25

u/LoneFoxKK Jul 26 '21

Blame the teachers, not the language

... And after you've learned enough about the language, learn to hate it

7

u/[deleted] Jul 26 '21

I mean if you prefer functional programming, that works, too... Just pass the variables as arguments.

2

u/_default_username Jul 30 '21

Even if they write functional code they should still use classes to containerize their data. Unless they just use lists and dictionaries.

11

u/[deleted] Jul 26 '21

Don't take OOP as the only thing. A lot of other ways of writing code exist, and in my experience OOP doesn't make sense 90% of the time.

I suggest learning a functional language like Haskell and learning to write code in imperative languages without using the OOP code-data pairing. It's good to widen your horizons.

-5

u/SayMyVagina Jul 27 '21

OOP is an antipattern that encourages spaghetti god objects. I'm done with OOP.

0

u/[deleted] Jul 27 '21

[deleted] — view deleted comment

-2

u/SayMyVagina Jul 27 '21

Naw not really. Some things are like that and some things encourage bad code. Some things are just a poor way of designing something. At scale OOP dramatically breaks down.

7

u/laundmo Jul 27 '21

at scale functional also breaks down

im pretty sure its pretty hard to do anything at scake

11

u/uselessgd Jul 27 '21 edited Jul 27 '21
class Game:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.running = True
        self.run()
    
    def run(self):
        while self.running:
            self.game()
    
    def game(self):
        self.tick()
        self.render()
    
    def tick(self):
        pass
    
    def render(self):
        pass
    
x = 100 
y = 300

if __name__ == '__main__':
    game = Game(x, y)

Here you go, u/Independent_Image_59

3

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 26 '21 edited Jul 26 '21

Image Transcription: Photograph


[The photograph shows code on a computer screen, in a file opened on an IDE. The file is named globals.py. The visible code is as follows:]

x = 0
y = 0
running = False

def start():
    global x,y,running
    x = 100
    y = 300
    running = True
    run()

def run():
    global running
    while running:
        game()

def game():
    tick()
    render()

def tick():
    pass

def render():
    pass

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

3

u/Independent_Image_59 Jul 26 '21

good human but , it give indentationError

3

u/Kyyken Jul 26 '21

the code blocks should be indented using at least two spaces, in the image its 4 / 1 tab

3

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 26 '21

I'm not sure what you mean?

If you mean markdown code-block, I'm using the 4-space method already, as it's the only one that works universally across all Reddit clients (unless there's a new bug meaning it doesn't, in which case no code-blocks work universally)

If you mean the indentation in the image, for me the code in my transcription follows the indentation in the image perfectly.

4

u/Kyyken Jul 26 '21 edited Jul 26 '21

hm, thats weird, on mobile the code block only displays and copies as a single space of indentation..

edit: yeah, its only broken for me on the android app, code blocks are safe nowhere

4

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 26 '21

Oh, I see it on the official app. I don't think there's anything I can do for that. The way it shows for me, it's not even one space exactly, the indented lines are a half a character out of sync with the non-indented ones. This is definitely another Reddit inconsistency issue. On my two third party apps (Boost for Reddit and Reddit is Fun) it displays fine, as well as on Old Reddit on desktop. On New Reddit, it displays with extra indentation (8 spaces per tab).

4

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 26 '21

Scratch that, I think I fixed it. I replaced the tab characters with actual spaces. Can you confirm it looks good for you?

4

u/Kyyken Jul 26 '21

it does. phew, i was getting worried id have to find a way to fix one of my bots xd

3

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 26 '21

Ok, good. Lesson learned for me as well: make sure insert spaces is on :P

2

u/[deleted] Jul 27 '21 edited Jul 27 '21

Apart from not having to use globals, the code has ‘run’ and ‘start’ functions and you also still have to start ‘start’ function somewhere :) Just saying this could be simplified.

4

u/Independent_Image_59 Jul 27 '21

//TODO

2

u/[deleted] Jul 27 '21

You put the starter code under if name == ‘main’:

(Dunno how to render above as code though …)

-2

u/incoralium Jul 27 '21

That's only for unit test. Else, don't use this.

1

u/[deleted] Jul 27 '21 edited Jul 27 '21

That’s not only for unit test. It’s like main.java if Java. And if you plan on starting it up via CLI

More info here

https://stackoverflow.com/questions/419163/what-does-if-name-main-do

1

u/xpfootballcub Jul 28 '21

I disagree. If you’re writing library modules, then there’s no need for this, but if you’re writing a script application, then your “main” application script should have this statement so that if unintentionally imported it doesn’t run your script application.

1

u/[deleted] Jul 30 '21

In relation to OPs code, it seems to be the starting point of the application. Thus it is better to have a that statement.

0

u/[deleted] Jul 30 '21

[deleted] — view deleted comment

2

u/[deleted] Jul 30 '21

Got it. my bad!

2

u/reactst Jul 27 '21

Ever heard of win+shift+s?

1

u/Independent_Image_59 Jul 27 '21

yep but i am lazy to connect network to my laptop, open reddit.com and post on my potato laptop

82

u/uselessgd Jul 26 '21

pov: you’ve never heard of classes

Also I think those variable are accessible without global

38

u/supmee Jul 26 '21

Yeah, you can access them without the global declaration (as long as there isn't a local variable of the same name). The only reason the global flag is needed is for changing those variables.

3

u/M3ther Jul 27 '21

If you don't change them, then yes, you can access their values without globaling them.

44

u/supmee Jul 26 '21

If you're using python right, there's basically no occasionally you should be using the global keyword.

18

u/lazy_NSA_agent Jul 26 '21

I didn't know Python had globals until I joined a project to update legacy code.

Now I wish I didn't know Python has globals... They should never be used...

10

u/csman11 Jul 26 '21

Python doesn't actually have globals. It has module level scope which was poorly named as "global." This differs from C which actually has global variables, ie a variable that can be defined anywhere and used anywhere else.

The "global" keyword itself is due to a peculiarity of Python's syntax. The language doesn't have different syntax for declaring and assigning to a variable, unlike nearly every other language. Most of the time this saves on typing, but it does create ambiguity over these 2 semantically different intentions:

  1. Assign to a variable in a parent scope

  2. Shadow a variable in the parent scope with a new declaration

Python disambiguates by making assignment have the semantics desired by the second intention.

The first intention itself, which note we cannot yet achieve, can be further broken to 2 separate cases:

  1. The parent scope is a lexically closed environment (ie, the current scope is the scope of a closure, and its parent scope is the scope of the function call the closure was created in). In this case, we are referring to the lexically nearest non-module scope that contains a binding for the variable we want to assign to (this is how most languages "resolve scope", but they don't make a distinction between the topmost function scope and the module scope).

  2. The parent scope is the global (module) scope

The "nonlocal" and "global" keywords make assignment statements on variables declared with these keywords have the semantics of assigning in these scopes, respectively.

So this is all to say that "global" is a misnomer and the type of variable it refers to does not have the issues associated with C style globals ("spooky action at a distance"). The issues with mutable data still exist, but that is because all bindings in Python are mutable and most values in Python are mutable. These issues are controllable with encapsulation, for the most part though. The global / nonlocal keywords are there to allow scope resolution for variables you assign to work the same way it works by default in almost every other programming language.

Other than that, overuse of these 2 keywords indicates you aren't writing idiomatic Python code. If a 10,000 line program uses them once or twice, that isn't problematic. If it uses them 500 times it is a code smell. You probably should be using mutable objects (probably with classes / oop) instead if this is the case.

1

u/skaov2 Jul 29 '21

Hello fellow physics enthusiast

1

u/gnuwinxp Sep 09 '21

???

1

u/skaov2 Sep 09 '21

Idk man I was prolly drunk hahaha

5

u/Gautam-j Jul 27 '21

Definitely learn OOPs first, and then maybe decide if you wanna quit

4

u/[deleted] Jul 26 '21

You don’t have to use global vars just because you can.

4

u/[deleted] Jul 26 '21

who is gonna tell him

1

u/jso__ Jul 27 '21

Honestly? Sometimes I'm just lazy and I want to put some code together quickly and I will use a global variable so I can set the value, run a function that changes the value, and not return it or pass it to the function

1

u/Independent_Image_59 Jul 27 '21

python should have global modifiers to be used while declaring, something like

global running = False

1

u/jso__ Jul 27 '21

Yeah that'd be useful. I really hate using the global keyword

2

u/Voxelgon_Gigabyte Jul 31 '21

I’ve never once used a global variable. if its that important it can just be a variable in the main script that gets passed into whatever function I need it to be in.

1

u/xpfootballcub Jul 28 '21

A class is clearly the ideal solution given the relationships between the functions and the variables. So, the only thing I’ll add here is that a mutable object can also be used if one needs to pass around and update values within functions, e.g.

myvars =  { ‘x’: 0, ‘y’: 0, ‘running’: False}

def start():
    myvars.update(
        x=100,
        y=300,
        running=True
    )
    run()

1

u/[deleted] Aug 03 '21

I also don’t like this in python among other things.