mapping None values to ''
Tim Chase
python.list at tim.thechases.com
Sun Jun 18 08:37:00 EDT 2006
> i wish to map None or "None" values to "".
> eg
> a = None
> b = None
> c = "None"
>
> map( <something> , [i for i in [a,b,c] if i in ("None",None) ])
>
> I can't seem to find a way to put all values to "". Can anyone help?
> thanks
I'd consider this a VeryBadIdea(tm). However, given Python's
introspective superpowers, it *can* be done (even if it most
likely *shouldn't* be done). That caveat out of the way, here goes:
>>> for scope in [locals, globals]:
... s = scope()
... for vbl, value in s.items():
... if value == None or (type(value) == type("") and
value == 'None'):
... s[vbl] = ''
seems to do the trick. You may, likely, just want to operate on
locals, not every last global variable in your project, in which
case you can just use
s = locals()
for vbl, value in s.items():
...
There may be some better way to determing whether an item is a
string than my off-the-cufff
type(value) == type("")
but it worked to prevent trying to compare non-strings to the
string 'None' later in the sub-clause of the if statement.
Note that if you wrap this in a function, you'll may have to pass
in locals() as a parameter because otherwise, inside your
function, you'll have a different set of available locals that
you did when you called the function. :)
Beware your foot when shooting this gun...it likes to aim at feet.
-tkc
More information about the Python-list
mailing list