Can global variable be passed into Python function?

Chris Angelico rosuav at
Sat Mar 1 07:24:15 CET 2014

On Sat, Mar 1, 2014 at 4:30 PM, Mark H. Harris <harrismh777 at> wrote:
> hi Chris,   yeah... well think again of the switch block in C...   the switch block selects a branch based on an integral number (int character) that is generally a return code from a function.  The function hides all of that logic. The function runs and returns a "number" which is passed to the switch block. That number generally corresponds to a DEFINE constant at the top or in the header...   so we get something really readable:
> x = somefunc()
> switch (x):
>   case: CONSTANT1
>        call blah blah
>   case: CONSTANT2
>        call blah blah blah
>   default
>        blah

Okay. So you'd do that to make this more readable. Here's the original:

    if (n**2 < D(1)):
        a = __atan__(n)
    elif (n == D(1)):
        a = gpi/4
    elif (n == D(-1)):
        a = -(gpi/4)
    elif (n < D(-1)):
        a = __atan__Lt_neg1__(n)
        a = __atan__Gt_1__(n)

Now let's see. Your code doesn't perfectly translate, so I'm having to
guess a bit here.

GT_1 = object()
LT_n1 = object()
IS_1 = object()
IS_n1 = object()
def categorize(n):
    if (n**2 < D(1)):
        return None
    elif (n == D(1)):
        return IS_1
    elif (n == D(-1)):
        return IS_n1
    elif (n < D(-1)):
        return LT_n1
        return GT_1

   switch categorize(x):
      case GT_1:
# Not sure which you mean, this
      case LT_n1:
# or this
      case LT_1:
# So I have both, ish.
      case IS_1:
         a = gpi/4
      case IS_n1:
         a = -gpi/4
# Presumably this should be a=?

Please copy and paste this, and then edit it so the two actually do
exactly the same thing. And then, if you please [1], explain to me how
the second one is more readable.  It still has the exact same if/elif
tree, because there's no other way to figure out which constant you
should have for the switch; and as well as that, it exhibits an
appalling degree of Soft Coding[2], and it's roughly three times as
much code. If you want to change anything, you potentially have to
edit three places: the list of constants at the top, the condition
function, and the switch.

This can't be your idea of readability. Show me where I'm wrong.


[1] Steven D'Aprano unwittingly quoted HMS Pinafore a few posts back.
I'm now doing it consciously, for I hold that (on the seas) the
expression "if you please" a particularly gentlemanly tone implants.


More information about the Python-list mailing list