Is it possible to create C-style "main" function in Python? (for teaching purposes)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Oct 4 22:06:14 EDT 2011


On Mon, 03 Oct 2011 21:27:12 -0700, alex23 wrote:

> rantingrick <rantingr... at gmail.com> wrote:
>> Why? Well because many times i find myself wondering if this or that
>> variable is local or global -- and when i say "global" i am speaking of
>> module scope! The "global<DOT>" cures the ill.
> 
> Given your stated propensity for huge code blocks not chunked into
> functions, I'm not surprised you lose track of what is global, what is
> nonlocal etc. This is another clear advantage of small functions: you
> can view it all at once. For the rest of us, a variable is global if its
> referenced but not defined in a specific scope. There's no need for such
> verbose hand-holding.
> 
> I'd say the wart is in your design practice rather than the language
> itself.

Furthermore, rick's suggestion that all globals should be referenced 
using an explicit global namespace would become extraordinarily horrible 
in practice. Let's take a simple example from the shutil module:

# From Python 2.5 shutil.py
def copystat(src, dst):
    """Copy all stat info (mode bits, atime and mtime) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)


Under Rick's proposal, that would be written:

def copystat(src, dst):
    """Copy all stat info (mode bits, atime and mtime) from src to dst"""
    st = global.os.stat(src)
    mode = global.stat.S_IMODE(st.st_mode)
    if global.hasattr(os, 'utime'):
        global.os.utime(dst, (st.st_atime, st.st_mtime))
    if global.hasattr(os, 'chmod'):
        global.os.chmod(dst, mode)


Imported modules are variables like any other, and as they usually exist 
in the global scope, so they will all need to be explicitly referenced as 
global. This will get tiresome very quickly, and is a cure far worse than 
the disease, and alone is enough to disqualify this suggestion from 
serious consideration.

Furthermore, "globals" in Python also includes the built-ins, so every 
reference to built-ins like len, sum, list, int, abs, etc. will also need 
an explicit reference, e.g. global.len, global.sum.

(The alternative would be a significantly different name-lookup strategy: 
instead of names being "local" vs "global or builtin", they would be 
"local or builtin" vs "global". This will break monkey-patching.)


-- 
Steven



More information about the Python-list mailing list