|
Re: Code Snippets
|
Posted: Aug 22, 2003 8:26 AM
|
|
> Hi! I'm kinda new to programming. In Python, is there a > way to insert a code snippet inline? Basically, I've got > some recurring code, and rather than type it out every > time, I'd like to be able to just write out one line of > code that refers to some prewritten chunk. Kind of like a > function, but not really. I could implement the same thing > in a function, but my code would suddenly get more > awkward. Am I doomed to go through what I've already done > just to replace the ugly spots with slightly less ugly > function calls?
I'm not sure what you're really after here. The closest thing I've ever seen, without really having a function call would be to assign a lambda function to a variable like this:
cs = lambda *args: ''.join(map(str,args)) print cs("a","b","c","d",1,2,3)
I got this from http://www.mindview.net/Books/Python/ThinkingInPython.html
Basically what you're asking about is similar to a goto in a lot of respects. Depending on how complex the logic is, you're probably best off just creating a function call. I'm not sure I understand how a function call would make your code that much more awkward than having a call to a code snippet. If you're using it that much where this is an issue, I would break it out now before you double the amount of times you call the code chunk.
If you have to update something on this six months from now, you'll thank yourself for having the logic in a single function call, rather than having to update multiple occurences of the same code.
|
|