Law of Demeter and Python
Is there a tool to check if a Python code conforms to the law of Demeter?
I found a mention of Demeter in pycheck开发者_开发问答er, but it seems that the tool understands this law different to what I expect: http://en.wikipedia.org/wiki/Law_of_Demeter
The definition from wikipedia: the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:
- O itself
- M's parameters
- any objects created/instantiated within M
- O's direct component objects
- a global variable, accessible by O, in the scope of M
The way this law is explained in the link you provide it is far too vague and subjective to be efficiently checked by any automated tool. You would need to think of specific rules that lead to code that abides by this law. Then you can check for these rules.
law of Demeter ... method M of an object O may only invoke the methods of the following kinds of objects:
- O itself -- i.e.
self
variables. Easy to see. - M's parameters -- i.e., local variables given by the parameters. That is to say, in
locals()
- any objects created/instantiated within M -- i.e., local variables. That is to say, in
locals()
- O's direct component objects -- i.e.,
self
variables. - a global variable, accessible by O, in the scope of M -- i.e., variables named in a
global
statement or implicit references to globals that are not found in the local namespace. That is to say inglobals()
.
Ummm.... There are no other variables accessible to a function, are there? Because of the way namespaces work, I don't see any possibility for breaking this law.
Do you have an example of Python code that breaks one of these rules?
How would you get access to another namespace?
You could probably break that law like this:
class SomeClass:
def someMethod(self):
self.getSomeOtherClass().someOtherMethod() # this breaks the law
def getSomeOtherClass(self):
class_ = SomeOtherClass()
return class_
Or no?
精彩评论