This question is difficult to answer... What I think is a good technique may be commonly used by others... Plus Python has a relatively simple solution to the problem...
Ternary Operator a = True if k in l else False
List Comprehension a = [ x for x in l if x > 0]
property decorator
class A:
def __init__(self, name=None):
self._name = name
@property
def name(self):
return str(len(self._name)) + self._name
a = A("test")
print(a.name)
Add another exception capture method supported from 2.4 to 3.3, see if anyone needs it, inspired by @felix21’s example
I would like to recommend a relatively new third-party library python-sh. I don’t know if it is off topic; if it is off topic, please delete this answer :)
from sh import cat, ifconfig, git
content = cat("somefile").stdout
print(ifconfig("wlan0"))
git.checkout("master")
Please see the documentation for details http://amoffat.github.com/sh/
There is a very peculiar multimethod library in PyPy. Its implementation Its testing
With this library, there is no need to write visitor patterns. You can write code like this:
from rpython.tool.pairtype import pairtype, pair
class CodeGen(object): pass
class JavaCodeGen(CodeGen): pass
class LispCodeGen(CodeGen): pass
class Ast(object): pass
class Identifier(Ast):
def __init__(self, name):
self.name = name
class FunctionCall(Ast):
def __init__(self, func, args):
self.func = func
self.args = args
class __extend__(pairtype(CodeGen, Identifier)):
def gen((cg, ident)):
return ident.name
class __extend__(pairtype(JavaCodeGen, FunctionCall)):
def gen((cg, funcall)):
funcrepr = pair(cg, funcall.func).gen()
argreprs = ', '.join(pair(cg, arg).gen() for arg in funcall.args)
return '%s(%s)' % (funcrepr, argreprs)
class __extend__(pairtype(LispCodeGen, FunctionCall)):
def gen((cg, funcall)):
listitems = [funcall.func] + funcall.args
listrepr = ' '.join(pair(cg, arg).gen() for arg in listitems)
return '(%s)' % listrepr
# Test
someast = FunctionCall(Identifier('f'),
[Identifier('x'),
FunctionCall(Identifier('g'),
[Identifier('x')])])
assert pair(JavaCodeGen(), someast).gen() == 'f(x, g(x))'
assert pair(LispCodeGen(), someast).gen() == '(f x (g x))'
This question is difficult to answer... What I think is a good technique may be commonly used by others... Plus Python has a relatively simple solution to the problem...
Ternary Operator
a = True if k in l else FalseList Comprehension
a = [ x for x in l if x > 0]propertydecoratorclass A: def __init__(self, name=None): self._name = name @property def name(self): return str(len(self._name)) + self._name a = A("test") print(a.name)Add another
exceptioncapture method supported from 2.4 to 3.3, see if anyone needs it, inspired by @felix21’s exampleimport sys try: ... except Exception: t, e = sys.exc_info()[:2] print(e)I’ll add one more. Heehee
A quick way to remove duplicates from linked lists in Python:
{}.fromkeys(mylist,0).keys()import traceback def asdf(): (filename,line_number,function_name,text)=traceback.extract_stack()[-1] print function_name asdf()Let’s add a pure python module pexpect, this thing is very good.
#!/usr/bin/python import sys import pexpect password = 'password' expect_list = ['(yes/no)', 'password:'] p = pexpect.spawn('ssh username@localhost ls') try: while True: idx = p.expect(expect_list) print p.before + expect_list[idx], if idx == 0: print "enter yes" p.sendline('yes') elif idx == 1: print "enter password" p.sendline(password) except pexpect.TIMEOUT: print >>sys.stderr, 'timeout' except pexpect.EOF: print p.beforeI would like to recommend a relatively new third-party library python-sh. I don’t know if it is off topic; if it is off topic, please delete this answer :)
from sh import cat, ifconfig, git content = cat("somefile").stdout print(ifconfig("wlan0")) git.checkout("master")Please see the documentation for details http://amoffat.github.com/sh/
I will write about the singleton pattern in Python here
class Singleton(object): """Singleton pattern Somehow singleton in python is useless class A: class_var = object() A() == A() ==> True """ _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__( cls, *args, **kwargs) return cls._instanceThere is a very peculiar multimethod library in PyPy. Its implementation Its testing
With this library, there is no need to write visitor patterns. You can write code like this:
from rpython.tool.pairtype import pairtype, pair class CodeGen(object): pass class JavaCodeGen(CodeGen): pass class LispCodeGen(CodeGen): pass class Ast(object): pass class Identifier(Ast): def __init__(self, name): self.name = name class FunctionCall(Ast): def __init__(self, func, args): self.func = func self.args = args class __extend__(pairtype(CodeGen, Identifier)): def gen((cg, ident)): return ident.name class __extend__(pairtype(JavaCodeGen, FunctionCall)): def gen((cg, funcall)): funcrepr = pair(cg, funcall.func).gen() argreprs = ', '.join(pair(cg, arg).gen() for arg in funcall.args) return '%s(%s)' % (funcrepr, argreprs) class __extend__(pairtype(LispCodeGen, FunctionCall)): def gen((cg, funcall)): listitems = [funcall.func] + funcall.args listrepr = ' '.join(pair(cg, arg).gen() for arg in listitems) return '(%s)' % listrepr # Test someast = FunctionCall(Identifier('f'), [Identifier('x'), FunctionCall(Identifier('g'), [Identifier('x')])]) assert pair(JavaCodeGen(), someast).gen() == 'f(x, g(x))' assert pair(LispCodeGen(), someast).gen() == '(f x (g x))'The zip function is rarely used, so I am a novice.