Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables and coding style recommendations

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()
like image 863
Dnaiel Avatar asked Mar 20 '13 15:03

Dnaiel


2 Answers

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.

  • Global Variables

  • Constants

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.

like image 124
mmoore Avatar answered Oct 23 '22 13:10

mmoore


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.

like image 22
Bartosz Dabrowski Avatar answered Oct 23 '22 12:10

Bartosz Dabrowski