Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Sun Mar 2 22:28:17 CET 2014


On Mon, Mar 3, 2014 at 8:03 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> If one were begging for trouble, one *could* define:
>
>    class ABC:
>        A = 1
>        B = 1.0
>        C = 1+0j

You're missing the point of flags, though. One does not use floats for
flags. Flags are normally going to be integers (passed directly to an
underlying C API), strings (self-documenting), or arbitrary objects
with no value beyond their identities. In all cases, value equality is
the normal way to recognize them, except in the special case of
bit-flag integers, where you use bitwise operations (and then equality
checks, possibly):

DIRECTORY = 512 # Not sure that one's right, tbh
OWNER_READ = 256
OWNER_WRITE = 128
OWNER_EXEC = 64
GROUP_READ = 32
...
OTHERS_EXEC = 1

mode = 1005
if mode & DIRECTORY:
    # It's a directory!
if mode & OTHERS_READ:
    # You're allowed to read (eg 'ls')
if mode & GROUP_EXEC:
    # You get the idea.

With multi-bit flags you might have to do a bitwise AND followed by an
equality check:

NOT_STICKY = 0
STICKY_PARTIAL = 16
STICKY_MOSTLY = 32
STICKY_ENTIRELY = 48
STICKY_BITS = 48

if style & STICKY_BITS == STICKY_MOSTLY:
    # I've no idea what this means, actually

At no time can you do identity checks. It might happen to work with
the lower bit values and CPython, but when you check the 2048 bit, you
don't get that. Value is all that matters.

ChrisA



More information about the Python-list mailing list