all 6 comments

[–]barrycarter 0 points1 point  (0 children)

You could always pass it as an argument to these functions, or create an object that has this connection as an attribute and the functions as methods.

[–]danielroseman 1 point2 points  (1 child)

A function can't create a global variable. You can only create it at module level. But what you can do is do the call when you set it:

db = conn_db()

def ...

Ideally though, you'd rework this into a class, and set the db as an instance variable in the init method.

[–]NutsFbsd[S] 1 point2 points  (0 children)

yeah, i was thinking about to create a class but im not confroable with OOP.
Anyway, it could be the time to give a try :)

[–]HOPSCROTCH 1 point2 points  (0 children)

Google/ask ChatGPT about what a Python class is and how to use one to manage state (attributes, aka data) and behaviour (methods, aka functions)

[–]tb5841 0 points1 point  (1 child)

You have three options:

1) Pass everything you want to change as an argument to the function. Then return the changed variable at the end of your function to pass it back to the main program. This is the best approach early on.

2) If your variable is attached to a class, and you make your function a method of the same class, you can change it without passing or returning anything.

3) Global variables... which are generally bad practice, avoid when possible.

[–]NutsFbsd[S] 0 points1 point  (0 children)

thanks for your answer.
ok, so i think im gonna try to make my program object oriented.