On 25 Mar 2005 10:09:50 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:
>I've never found any need for an is_defined function. If in doubt I just >make sure and initialise all variables to a suitable value before use. >However, I'll assume you have a good use case. I admit that that is the better practice. George's example was the conversion of data from one form to another where the data is mixed with complete and incomplete items. And Kay is looking at tuple unpacking. It's hard to beat try/except for these situations though. :) I cleaned it up some more and figured out the proper use of _getframe(). So no lambdas, and no passing of locals needed., and it checks for globals and builtins before defining the default value so as not to over write a readable value. I'm not sure what the best behavior should be. Maybe a routine to tell where a name is, ie.. local, global, builtin, or a writable global? maybe isa() return the location or None.? I think that would be better. The best purpose for utilities like these is for debugging and getting feedback about the environment. So I'm thinking of putting them in a module for that purpose. I have a subroutine to list all the names attached to an object. I think I can add that a bit now too. #---Here's the code--------------------- import sys def isa(v): """ Check if a varable exists in the current (parent to this function), global, or builtin name spaces. use: bool = isa( str ) returns True or False """ plocals = sys._getframe(1).f_locals if plocals.has_key(v) or globals().has_key(v) or \ __builtins__.locals().has_key(v): return True return False def ifno(v, obj=None): """ Check if a varable does not exists, return a default value, otherwise return the varable obj. use: obj = ifno( str [,obj=None] ) if str exist, returns str's object if str does not exist, returns specified object """ plocals = sys._getframe(1).f_locals if plocals.has_key(v): return plocals[v] if globals().has_key(v): return globals()[v] if __builtins__.locals().has_key(v): return __builtins__.locals()[v] return obj def test(): """ Test isa() and ifno() functions: """ # Totally useless routine. ;) import random for n in range(25): # Delete a random x,y,z coordinate to # simulate an unrealiabe data source. d = random.choice([1,2,3]) if d==1: if isa('x'): del x elif d==2: if isa('y'): del y else: if isa('z'): del z # Replace the missing Varible with a random number. r = int(random.random()*100) x, y, z = ifno('x',r), ifno('y',r), ifno('z',r) print x, y, z if __name__ == '__main__': test() #------------------------------------- -- http://mail.python.org/mailman/listinfo/python-list