D
D
Daniel2021-07-11 16:13:56
Python
Daniel, 2021-07-11 16:13:56

Is using a global variable considered shitty code?

I am freelancing and when I did the project I used something like data = {key: value} and imported it into some functions as global data. When I handed over the project, this moment was said to be redone without explanation. Why?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
ScriptKiddo, 2021-07-11
@DanielWorker

Yes. Global variables are an anti-pattern in many, if not all, programming languages.

P
pcdesign, 2021-07-11
@pcdesign

Global variables are a normal tool. For example. here is from the official flask documentation. As an example of using a global variable to store a database connection.

from flask import g

def get_db():
    if 'db' not in g:
        g.db = connect_to_database()

    return g.db

https://flask.palletsprojects.com/en/2.0.x/appcontext/
Saying that global variables are an antipattern is like saying that an ax is evil. Raskolnikov killed his grandmother with an ax ... If someone shoots himself in the foot using global variables, well, this is the shooter's problem.

D
Daniel, 2021-07-11
@DanielWorker

These words completely close the question:

Global variables are an antipattern

And in particular, the creator of the Python language himself spoke out that the global operator was introduced into the language as a marker of bad code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question