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".
"""Assign empty dictionary to variable if None.
Pydev script for generating code that tests if a variable is none, and if
so, assigns an empty dictionary to it.
This script is bound to "Ctrl-2 d" in PyDev by default, and must be
executed at a line containing only one alphanumeric word in order to have
any effect. Otherwise the script will just fling a popup at you and make no
changes to your code.
Example
=======
Before:
-----------------------------------------------------------------------
class Cow(object):
def translate(self, phrases = None):
'''Cow to English translation. None means translate nothing.'''
phrase
for phrase in phrases.items():
print "%r means %r in Cow." % phrase
-----------------------------------------------------------------------
Executing this script at the "phrases" line will change the code like so:
After:
-----------------------------------------------------------------------
class Cow(object):
def translate(self, phrases = None):
'''Cow to English translation. None means translate nothing.'''
if phrases is None:
phrases = dict()
for phrase in phrases.items():
print "%r means %r in Cow." % phrase
-----------------------------------------------------------------------
Note that this script does not check if phrases is defined or valid in any
other way.
"""
__author__ = "Joel Hedlund <[EMAIL PROTECTED]>"
__version__ = "1.0.0"
__copyright__ = """\
This script is available under the same conditions as PyDev.
See PyDev license for details.
"""
__support__ = """Contact the author for bug reports/feature requests."""
# This is a magic trick that tells the PyDev Extensions editor
# about the namespace provided for pydev scripts:
if False:
from org.python.pydev.editor import PyEdit [EMAIL PROTECTED]
cmd = 'command string'
editor = PyEdit
assert cmd is not None
assert editor is not None
from org.python.pydev.jython import ExitScriptException
# 'onSave' can be added to the list for developing purposes.
if cmd not in ['onCreateActions']:
raise ExitScriptException
import re
from java.lang import StringBuffer
from org.eclipse.jface.action import Action [EMAIL PROTECTED]
from org.eclipse.jface.dialogs import MessageDialog [EMAIL PROTECTED]
from org.python.pydev.core.docutils import PySelection [EMAIL PROTECTED]
from org.python.pydev.editor.actions import PyAction [EMAIL PROTECTED]
from org.python.pydev.core.docutils import ParsingUtils [EMAIL PROTECTED]
class ScriptUnapplicableError(Exception):
"""Raised when the script is unapplicable to the current line."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class UseEmptyDictIfNone(Action):
"""Assign empty dict to variable if None.
See module docs for details.
"""
_rName = re.compile(r'^ *(\w+)\s*$')
_sNewline = '\r\n'
def _scriptApplicable(self, selection):
"""Popup error message and return False if script is unapplicable.
@param selection: The current selection as a PySelection.
"""
sCurrentLine = selection.getCursorLineContents()
if not self._rName.match(sCurrentLine):
sTitle = "Script Unapplicable"
sHeader = "Script: Use empty dict if None"
sUse = ("Use: Generate code to check if variable is None, and "
"if so, assign an empty dictionary to it.")
sBody = ("This script can only be run if the current line "
"contains exactly one alphanumeric word.")
lsText = [sHeader, sUse, '', 'Error:', sBody]
sDialogText = self._sNewline.join(lsText)
oShell = editor.getSite().getShell()
MessageDialog.openInformation(oShell, sTitle, sDialogText)
return False
return True
def run(self):
oSelection = PySelection(editor)
oDocument = editor.getDocument()
self._sNewLine = PyAction.getDelimiter(oDocument)
if not self._scriptApplicable(oSelection):
return None
# Build the new code:
sOldLine = oSelection.getCursorLineContents()
sName = self._rName.match(sOldLine).group(1)
sInitial = PySelection.getIndentationFromLine(sOldLine)
sTempl = ("%(initial)sif %(name)s is None:%(newline)s"
"%(initial)s%(indent)s%(name)s = dict()")
dssVars = {'initial': sInitial,
'name': sName,
'indent': PyAction.getStaticIndentationString(editor),
'newline': self._sNewline}
sNewCode = sTempl % dssVars
# Move to insert point:
iStartLineOffset = oSelection.getLineOffset()
iEndLineOffset = iStartLineOffset + len(sOldLine)
editor.setSelection(iEndLineOffset, 0)
oSelection = PySelection(editor)
# Replace the old line with the new assignment expression:
oSelection.replaceLineContentsToSelection(sNewCode)
del oSelection
sDescription = 'Use empty dict if None'
editor.addOfflineActionListener("d", UseEmptyDictIfNone(), sDescription, False)
"""Assign empty list to variable if None.
Pydev script for generating code that tests if a variable is none, and if
so, assigns an empty list to it.
This script is bound to "Ctrl-2 l" in PyDev by default, and must be
executed at a line containing only one alphanumeric word in order to have
any effect. Otherwise the script will just fling a popup at you and make no
changes to your code.
Example
=======
Before:
------------------------------------------------------------
class Cow(object):
def eat(self, meals = None):
'''Ingest a series of meals. None means no meals.'''
meals
for meal in meals:
print "Moo! I like %s." % meal
------------------------------------------------------------
Executing this script at the "meals" line will change the code like so:
After:
------------------------------------------------------------
class Cow(object):
def eat(self, meals = None):
'''Ingest a series of meals. None means no meals.'''
if meals is None:
meals = list()
for meal in meals:
print "Moo! I like %s." % meal
------------------------------------------------------------
Note that this script does not check if meals is defined or valid in any
other way.
"""
__author__ = "Joel Hedlund <[EMAIL PROTECTED]>"
__version__ = "1.0.0"
__copyright__ = """\
This script is available under the same conditions as PyDev.
See PyDev license for details.
"""
__support__ = """Contact the author for bug reports/feature requests."""
# This is a magic trick that tells the PyDev Extensions editor
# about the namespace provided for pydev scripts:
if False:
from org.python.pydev.editor import PyEdit [EMAIL PROTECTED]
cmd = 'command string'
editor = PyEdit
assert cmd is not None
assert editor is not None
from org.python.pydev.jython import ExitScriptException
# 'onSave' can be added to the list for developing purposes.
if cmd not in ['onCreateActions']:
raise ExitScriptException
import re
from java.lang import StringBuffer
from org.eclipse.jface.action import Action [EMAIL PROTECTED]
from org.eclipse.jface.dialogs import MessageDialog [EMAIL PROTECTED]
from org.python.pydev.core.docutils import PySelection [EMAIL PROTECTED]
from org.python.pydev.editor.actions import PyAction [EMAIL PROTECTED]
from org.python.pydev.core.docutils import ParsingUtils [EMAIL PROTECTED]
class ScriptUnapplicableError(Exception):
"""Raised when the script is unapplicable to the current line."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class UseEmptyListIfNone(Action):
"""Assign empty list to variable if None.
See module docs for further details.
"""
_rName = re.compile(r'^ *(\w+)\s*$')
_sNewline = '\r\n'
def _scriptApplicable(self, selection):
"""Popup error message and return False if script is unapplicable.
@param selection: The current selection as a PySelection.
"""
sCurrentLine = selection.getCursorLineContents()
if not self._rName.match(sCurrentLine):
sTitle = "Script Unapplicable"
sHeader = "Script: Use empty list if None"
sUse = ("Use: Generate code to check if variable is None, and "
"if so, assign an empty list to it.")
sBody = ("This script can only be run if the current line "
"contains exactly one alphanumeric word.")
lsText = [sHeader, sUse, '', 'Error:', sBody]
sDialogText = self._sNewline.join(lsText)
oShell = editor.getSite().getShell()
MessageDialog.openInformation(oShell, sTitle, sDialogText)
return False
return True
def run(self):
oSelection = PySelection(editor)
oDocument = editor.getDocument()
self._sNewLine = PyAction.getDelimiter(oDocument)
if not self._scriptApplicable(oSelection):
return None
# Build the new code:
sOldLine = oSelection.getCursorLineContents()
sName = self._rName.match(sOldLine).group(1)
sInitial = PySelection.getIndentationFromLine(sOldLine)
sTempl = ("%(initial)sif %(name)s is None:%(newline)s"
"%(initial)s%(indent)s%(name)s = list()")
dssVars = {'initial': sInitial,
'name': sName,
'indent': PyAction.getStaticIndentationString(editor),
'newline': self._sNewline}
sNewCode = sTempl % dssVars
# Move to insert point:
iStartLineOffset = oSelection.getLineOffset()
iEndLineOffset = iStartLineOffset + len(sOldLine)
editor.setSelection(iEndLineOffset, 0)
oSelection = PySelection(editor)
# Replace the old line with the new assignment expression:
oSelection.replaceLineContentsToSelection(sNewCode)
del oSelection
sDescription = 'Use empty list if None'
editor.addOfflineActionListener("l", UseEmptyListIfNone(), sDescription, False)
"""Assign an attribute of self to variable, if variable is None.
Pydev script for generating code that checks if a variable is None, and if
so, assigns it the value of an attribute of self with the same name.
This script is bound to "Ctrl-2 s" in PyDev by default, and must be
executed at an indented line containing only one alphanumeric word in order
to have any effect. Otherwise the script will just fling a popup at you and
make no changes to your code.
Example
=======
Before:
----------------------------------------------------------
class Cow(object):
wisdom = "Grass be greener on other side of pasture."
def moo(self, wisdom = None):
'''Deliver wisdom verbally, bovine style.
None means deliver generic cow lore.
'''
wisdom
print wisdom
----------------------------------------------------------
Executing this script at the "wisdom" line will replace the word "wisdom"
with new code like so:
After:
----------------------------------------------------------
class Cow(object):
wisdom = "Grass be greener on other side of pasture."
def moo(self, wisdom = None):
'''Deliver wisdom verbally, bovine style.
None means deliver generic cow lore.
'''
if wisdom is None:
wisdom = self.wisdom
print wisdom
----------------------------------------------------------
Note that this script does not check if "wisdom" is defined or valid in any
other way.
"""
__author__ = "Joel Hedlund <[EMAIL PROTECTED]>"
__version__ = "1.0.0"
__copyright__ = """\
This script is available under the same conditions as PyDev.
See PyDev license for details.
"""
__support__ = """Contact the author for bug reports/feature requests."""
# This is a magic trick that tells the PyDev Extensions editor
# about the namespace provided for pydev scripts:
if False:
from org.python.pydev.editor import PyEdit [EMAIL PROTECTED]
cmd = 'command string'
editor = PyEdit
assert cmd is not None
assert editor is not None
from org.python.pydev.jython import ExitScriptException
# 'onSave' can be added to the list for developing purposes.
if cmd not in ['onCreateActions']:
raise ExitScriptException
import re
from java.lang import StringBuffer
from org.eclipse.jface.action import Action [EMAIL PROTECTED]
from org.eclipse.jface.dialogs import MessageDialog [EMAIL PROTECTED]
from org.python.pydev.core.docutils import PySelection [EMAIL PROTECTED]
from org.python.pydev.editor.actions import PyAction [EMAIL PROTECTED]
from org.python.pydev.core.docutils import ParsingUtils [EMAIL PROTECTED]
class ScriptUnapplicableError(Exception):
"""Raised when the script is unapplicable to the current line."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class UseAttribOfSelfIfNone(Action):
"""Assign an attribute of self to variable, if variable is None.
See module docs for details.
"""
_rName = re.compile(r'^ {8} *(\w+)\s*$')
_sNewline = '\r\n'
def _scriptApplicable(self, selection):
"""Popup error message and return False if script is unapplicable.
@param selection: The current selection as a PySelection.
"""
sCurrentLine = selection.getCursorLineContents()
if not self._rName.match(sCurrentLine):
sTitle = "Script Unapplicable"
sHeader = "Script: Use attribute of self if None"
sUse = ("Use: Generate code to check if variable is None, and "
"if so, assign an attribute of self with the same "
"name to it.")
sBody = ("This script can only be run if the current line "
"contains exactly one alphanumeric word indented by at "
"least 8 spaces.")
lsText = [sHeader, sUse, '', 'Error:', sBody]
sDialogText = self._sNewline.join(lsText)
oShell = editor.getSite().getShell()
MessageDialog.openInformation(oShell, sTitle, sDialogText)
return False
return True
def run(self):
oSelection = PySelection(editor)
oDocument = editor.getDocument()
self._sNewLine = PyAction.getDelimiter(oDocument)
if not self._scriptApplicable(oSelection):
return None
# Build the new code:
sOldLine = oSelection.getCursorLineContents()
sName = self._rName.match(sOldLine).group(1)
sInitial = PySelection.getIndentationFromLine(sOldLine)
sTempl = ("%(initial)sif %(name)s is None:%(newline)s"
"%(initial)s%(indent)s%(name)s = self.%(name)s")
dssVars = {'initial': sInitial,
'name': sName,
'indent': PyAction.getStaticIndentationString(editor),
'newline': self._sNewline}
sNewCode = sTempl % dssVars
# Move to insert point:
iStartLineOffset = oSelection.getLineOffset()
iEndLineOffset = iStartLineOffset + len(sOldLine)
editor.setSelection(iEndLineOffset, 0)
oSelection = PySelection(editor)
# Replace the old line with the new assignment expression:
oSelection.replaceLineContentsToSelection(sNewCode)
del oSelection
sDescription = 'Use attribute of self if None'
editor.addOfflineActionListener("s", UseAttribOfSelfIfNone(), sDescription,
False)
-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
pydev-code mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/pydev-code