LangProc / langproc-2017-cw

1 stars 4 forks source link

Python global var #9

Open patrickjohncyh opened 6 years ago

patrickjohncyh commented 6 years ago

Do we declare a global variable within a function only if the variable is used? It appears that since we do not need to handle shadowing, it doesn't really matter if we declare extra global variables within a python function definition.

m8pple commented 6 years ago

As you say, because shadowing won't occur (for this deliverable), the declaration of a global variable in a function that doesn't use it shouldn't matter - it has no impact on the function, and isn't actually detectable at run-time.

So if you find it more convenient (and it is quite likely you will, hence your question :) ), the feel free.

In some ways this is similar to the approach used for languages like C for header files. If you want to use fprintf, you need to #include <stdio.h>, but this actually brings in declarations for loads of other functions as well. However, this should be safe, because according to the C standard identifiers coming from the C library are reserved. So a C compliant program should not define things called exit, or atoi, and there is no possibility of aliasing/shadowing. (If you do bare-metal/embedded programming then this changes, as you often end being the person defining things like malloc and putchar, because there is no C library available).