English 中文(简体)
粉碎
原标题:Styling long chains in Python
  • 时间:2012-01-11 11:29:51
  •  标签:
  • python

I ve written a Python API that is "chain based" (similar to jQuery). So I can write:

myObject.doStuff().doMoreStuf().goRed().goBlue().die()

The problem is that I haven t found a way to keep the syntax clean with long chains. In JavaScript I could simply do

myOjbect
   .doStuf()
   .doMoreStuf()
   .goRed()
   .goBlue()
   .die()

但是,Zazz的种植受到限制......

最佳回答

PEP8-compliant solution: formatting the line

实际上,PEP8 :

Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately.

因此,我赞成你的守则。

(
    myOjbect
    .doStuf()
    .doMoreStuf()
    .goRed()
    .goBlue()
    .die()
)

Alternative solutions: splitting into separate statements

依据《公约》第2条,在每种方法回归的数值方面,可以选择两种办法:

  1. Every method (maybe except die(), which is not required, as its result is not being used) returns modified instance (the same instance, on which it was called).
  2. Every method (still, die() is not required to do that) returns copy of the instance on which it was called.

Solution for mutable objects (methods return original instance)

In first case (when returning same instance), the solution to split longer lines into several statements is:

myObject.doStuf()
myObject.doMoreStuf()
myObject.goRed()
myObject.goBlue()
myObject.die()

真正的世界例子涉及 objects:

my_stuff = []
my_stuff.append( laptop )  # my_stuff == [ laptop ]
my_stuff.append( jacket )  # my_stuff == [ laptop ,  jacket ]
my_stuff.append( apple )  # my_stuff == [ laptop ,  jacket ,  apple ]

(虽然list.append() is not Return any, only for行文一致 and forclar that it is mutable)

Solution for immutable objects (methods return modified copy)

second case(在交回本时),类似的解决办法是:

myObject = myObject.doStuf()
myObject = myObject.doMoreStuf()
myObject = myObject.goRed()
myObject = myObject.goBlue()
myObject.die()

真正的世界例子涉及不可改变的物体:

name =  -Tadek- 
name = name.strip( - )  # name ==  Tadek 
name = name.lower()  # name ==  tadek 
name = name.replace( k ,  ck )  # name ==  tadeck 
问题回答
myOjbect 
   .doStuf() 
   .doMoreStuf() 
   .goRed() 
   .goBlue() 
   .die()

(我对<代码>myObject感到担忧。) 所有这一切都非常痛苦。

虽然我叫它“是”,但有可能在括号内打破:

myOjbect.doStuf(
   ).doMoreStuf(arg1, arg2
   ).goRed(
   ).goBlue(
   ).die()

但是,Tastes有差异,因此,我把它放在一个完整的答案上。

我发现,使“链条”看冰的好办法是简单地增加一线:

obj = myObject.doStuff()
obj = obj.doMoreStuf()
obj = obj.goRed()
obj = obj.goBlue()
obj = obj.die()

或者更好:使用有意义的名称,使守则更加明显。

obj = myObject.doStuff().doMoreStuf()
colored_object = obj.goRed().goBlue()
colored_object.die()

I don t think chained methods like this are used very commonly in python (if at all). One option would be to use an API that looks like

myObject.do(
     Stuff ,
     MoreStuff ,
     Red ,
     Blue ,
     die ,
    )

如果你给我们一个真正的榜样的话,你可能会得到更相关的建议,但很难猜测这里有什么样的行动。 或许其中一些应合并,或放在<条码>_init__。 (例如,彩色可以通过向_init 通过任择论据加以确定。)





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签