Jan.O hat geschrieben:Wolltest du damit vor 1,25 Jahren sagen, dass diese Methode Variablen zu globalisieren nach der Python-Philosophie nicht verwerflich ist?
Hallo Jan.O!
Ich weiß nicht, was du mich damit fragen möchtest. Aber das was ich damals sagen wollte ist, dass es bessere Möglichkeiten gibt, eine Variable "global" für alle in das Programm eingebundenen Module zu halten.
Da ich mich mit SQLAlchemy nicht auskenne, kann ich dir bei deinem Problem nicht helfen. Aber wenn du eine Variable global für alle Programmmodule halten willst, dann musst du diese Variable nur in ein Modul schreiben und dieses Modul in jedem anderen Modul importieren, in welchem du diese Variable brauchst.
globalvars.py:
Code: Alles auswählen
#!/usr/bin/env python
#coding: utf-8
# globalvars.py
global_value_a = 10
global_value_b = 20
module1.py:
Code: Alles auswählen
#!/usr/bin/env python
#coding: utf-8
# module1.py
import globalvars
def print_globalvars():
print globalvars.global_value_a
print globalvars.global_value_b
globalvars.global_value_a = 11
globalvars.global_value_b = 21
module2.py:
Code: Alles auswählen
#!/usr/bin/env python
#coding: utf-8
# module2.py
import globalvars
def print_globalvars():
print globalvars.global_value_a
print globalvars.global_value_b
globalvars.global_value_a = 12
globalvars.global_value_b = 22
myprogram.py:
Code: Alles auswählen
#!/usr/bin/env python
#coding: utf-8
# my_program.py
import globalvars
import module1
import module2
def main():
module1.print_globalvars()
module2.print_globalvars()
print globalvars.global_value_a
print globalvars.global_value_b
if __name__ == "__main__":
main()
Das löst aber nicht dein Threading-Problem. Außerdem ist es ratsamer, alle benötigten Objekte beim Aufruf einer Funktion an diese zu übergeben -- und nicht irgendwoher von einem globalen Variablen-Modul zu holen.
Wenn ich von mehreren Threads aus Zugriff auf eine Datenbank brauche, dann bekommt jeder Thread eine eigene Connection. Fertig Aus! Und die Sache ist gegessen. Wie das bei SQLAlchemy läuft, weiß ich nicht.
mfg
Gerold
