Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

normal way of using variables throughout python

Tags:

python

What is the standard way of declaring configuration variables for your program at the top of a python script? These are used throughout the program in multiple classes and functions. Is the best way:

  1. To create a mixed dictionary with the configuration options, and pass these to any classes that need them. Downside: this requires passing extra attributes. For example:

    config = {'parseTags': {'title','font','p'},    
        'name': 'steve',                
        'logFrequencies': 10,               
        'print_rate': False  
        }
    

     

    newCustomObject = CustomClass(config)
    customfunction(config)
    print 'hi',config['name']
    
  2. Create global variables at the beginning of the file and call those throughout the program. Downside: ruins the encapsulation of the classes.

  3. Something else.

What is the most pythonic way of doing this?

like image 366
Zach Avatar asked Jan 17 '23 07:01

Zach


1 Answers

For constants used in a single file (module), I usually just declare global variables at the top. This does not lose encapsulation in any meaningful way (it's no different from putting those constants in a base class that every class inherits from).

The django config system provides a nice way to create shared constants: you create a module, and the config system creates a read-only object from it, exposing the members of the module.

like image 96
Marcin Avatar answered Jan 19 '23 00:01

Marcin