'Program design - update global variable value
Suppose I have a global variable pi=3.14 in a script. In most cases, the pi is used as 3.14 in functions and classes in the script. However, the user might need to change the value sometimes. Can the user change the value of pi in the script without modifying the script? (The user don't want to pass the pi to the function as argument.)
For example, the user defines his own pi in another script or Jupyter notebook, and import the relevant functions and classes. Then, the functions and classes will use the new pi. From a software design perspective, is there a good way to do that?
Thank you in advance!
Solution 1:[1]
In general it's a bad practice to set globals into the python builtins if this is not completely necessary.
Here's what I would have done:
# foo_module.constants.py
class Constants:
# set them as class variables
pi: float = 3.14
phi: float = 1.61
your functions and classes:
# foo_module.my_application
from .constants import Constants
def circle_area(r):
return Constants.pi * (r ** 2)
class Circumfator:
def __init__(self):
self.pi = Constants.pi
def get_circumference(self, r):
return 2 * r * self.pi
Users perceptive:
from foo_package.my_application import *
circle_area(10) # returns 314.0
Circumfator().get_circumference(50) # returns 314.0
# user changes pi
Constants.pi = 1
circle_area(10) # returns 100
Circumfator().get_circumference(50) # returns 100
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
