[Pydev-code] New pydev jython scripts: Assign stuff to variable if it is None
Brought to you by:
fabioz
From: Joel H. <yo...@if...> - 2006-09-12 13:15:44
|
Hi! I hacked up a couple more little code generators for stuff that I seem to do over and over again. 1) Check variable and assign list() to it if it is None. 2) Check variable and assign dict() to it if it is None. 3) Check variable and assign an attribute of self with same name to it if it is None. I've bound the scripts like so: 1) "Ctrl-2 l" (for List) 2) "Ctrl-2 d" (for Dictionary) 3) "Ctrl-2 s" (for Self) Pop them in your Pydev Jython script dir, open a new editor and assign away! They should be self explanatory, and I've done all I can to prevent them from messing up your code. The docs are in the sources if you need them. Let me know what you think about them! Motivation and use cases follow below. Fabio >> Is there any chance that you'll be able to pop these into the quick assistant? Cheers! /Joel Motivation and use cases: The first 2 i frequently use to avoid having mutable default values in methods/functions. Example: # BAD! DANGER! Default arg value may change between calls! def fcn(arg = list()): do_stuff_with_arg # Good: def fcn(arg = None): if arg is None: arg = list() do_stuff_with_arg Writing those "if arg..." constructs quickly gets boring if there are many args. Scripts 1 and 2 will do those for you if you just write "arg" and hit "Ctrl-2" followed by "d" or "l" depending on if you want a dict or a list. The third is good for generalized methods. That is, those that are supposed to do something using a data member, but also just as well could do the same thing to an argument of the proper type. # Good: class GPS(object): def to_str(self): return "Long: %s, Lat:%s" % (coord.x, coord.y) # Better: class GPS(object): def to_str(self, coord = None): if coord is None: coord = self.coord return "Long: %s, Lat:%s" % (coord.x, coord.y) Just as for the first two, the third one will do those "if coord..." for you if you just write "coord" and hit "Ctrl-2" followed by "s". |