14

This question is quite general but it's more for me to understand good coding practices in python...

I'd like to define a constant that I can use inside in any function without having to pass it as argument, and without the need to change it anywhere after its declared - maybe it'd be nice to make it impossible to change but not sure if i can do that.

What'd be the best way to do this, in terms of programming style (coding, name convention, etc.)

I.e., GLOBAL_CONSTANT='this_variable_will_not_be_changed'

My python code would have this form, is it good style as well?

#!/usr/bin/env python

import sys
import os

GLOBAL_CONSTANT='this_variable_will_not_be_changed'

def test():
    print GLOBAL_CONSTANT
    return 0

def main():
    test()
    return 0

if __name__ == "__main__":
    main()
Dnaiel
  • 7,622
  • 23
  • 67
  • 126
  • 4
    Have a look at PEP 8: http://www.python.org/dev/peps/pep-0008/ – Alfe Mar 20 '13 at 15:41
  • 5
    I usually start like this for small scripts, and as the code grows, I encapsulate it in a class so that the global variable becomes a class variable. – yoniLavi Mar 20 '13 at 16:12

2 Answers2

10

Your code doesn't really do anything, so I guess it's fine! With regards to styling your code, refer to PEP 8 whenever you're in doubt.

With no more information than you've already given us, I'd have to say your conventions are ok.

Strictly adhering to PEP-8 isn't necessary however. The general consensus tends to be "Keep your code consistent". It can be confusing reading through a PEP-8 formatted file only to stumble into "blocks" of Java-esque or Hungarian notation code.

Martin
  • 830
  • 1
  • 7
  • 24
3

In 99% cases this is enough. But if you extremely need this value really constant you can check this

BTW: It will be hard way to learn Python by reflecting everything in other languages. Try forget past. Learn think Pythonic.

Community
  • 1
  • 1
Bartosz Dabrowski
  • 1,850
  • 2
  • 15
  • 21