0

I'm very new to python and would like to understand what is the pythonic way to define some contants. I have the following class:

class ConfigBuilder:

   def add_param(self, key, value):
       #...
   def build():
       #...

Now I want to use this in another module as follows:

some_val = #...
config_builder builder = ConfigBuilder()
builder.add_param('PROJECT_RELATED_KEY', some_val)

Where to put this 'PROJECT_RELATED_KEY'? In another module and then import it? Or put it as a global variable?

6
  • 3
    It's a matter of preference, wouldn't you say? You could do either, or neither. Commented Nov 14, 2017 at 19:50
  • @cᴏʟᴅsᴘᴇᴇᴅ I asked this because python seems to me more "conventional" language. Maybe there is some convention for it too. Commented Nov 14, 2017 at 19:50
  • 2
    For example: stackoverflow.com/a/18225046/4909087 Commented Nov 14, 2017 at 19:51
  • python.org/dev/peps/pep-0020 Commented Nov 14, 2017 at 19:52
  • The only convention is described in PEP 8 - Style Guide for Python Code in the section on Constants. A good place to put them depends on usage, but generally at the beginning (of a module or function). Commented Nov 14, 2017 at 19:55

1 Answer 1

1

Agreed that there is no absolute convention for where settings should be stored. There's a lot of flexibility when it comes to project placement. Below are a few possibilities I might consider when deciding where to put my own settings.

If your project might contains some sensitive parameters that you wouldn't want in version control, you could put them into your environment and then access them with environment variables.

import os
print os.environ['HOME']

If they're not sensitive at all, one possible route would be to do what Django does and create a settings.py file. Something like this

# myproject/settings.py
SOME_VALUE = 'SomeConfigurableValue'
FOO = 'bar'
PROJECT_RELATED_KEY = 'bestkeyever'

# myproject/builder.py
from myproject.settings import SOME_VALUE
print(SOME_VALUE)

You could even set up the project as a package and then do

from . import settings
print(settings.SOME_VALUE)

For more info on setting up a project as a package, see: How to fix "Attempted relative import in non-package" even with __init__.py

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.