tags:

views:

114

answers:

3

I'm just starting getting into Python - my focus being on using it with Maya and its API - and I've found that when I'm working on something there's, generally, at least 2 or 3 ways to do the same thing that I'm trying to do. For instance:

for key, value in locNameConnector.iteritems():
    value = locNameConnector[key]
    cmds.connectJoint(value, key, pm=True)

or

for name in locNameConnector:
    cmds.connectJoint(locNameConnector[name][0], name, pm=True)

now the code is calling specific things in Maya, but my question is, which way is more correct? I feel like the first one is because it's taking advantage of Python's power, while the second one could be written in any language. Is there a more correct way? Is one faster than the other?

A: 

I follow the principal "Anything that works is good". Asking yourself -which way would suite me/my code/the application best is more than enough.
But hardcore-python-programmers get very angry if they see any python code which is not "pythonic". A good read for that is here.

lalli
I understand where you're coming from with that. I just want to make sure that if I'm using a specific language for a specific purpose that I'm doing it the best way that the language has to offer. :) Thanks for the link too. Very interesting read (with examples that I myself am using that are not pythonic - but I'll change that soon). :)
ArrantSquid
+3  A: 

One of Python's philosophies is:

There should be one -- and preferably only one -- obvious way to do it.

(You can see a list of these - known as The Zen of Python - by doing import this in the Python shell.)

And Python does try and make it so that there really is only one way. But for any language beyond a very basic level of functionality, though, there is always going to be more than one way to do anything non-trivial - that's simply the way programming is. But even when there is more than one way, there is usually one that's regarded as more 'Pythonic'.

As regards your actual examples, they don't seem to be equivalent - the first one is looking up value in l_LegJointConnectors, the second looks it up in locNameConnector. Is that second line in the first example supposed to be there? If not, the first one is very definitely more Pythonic than the second.

Daniel Roseman
Thank you for pointing out the error in naming. It was incorrect.
ArrantSquid
Thank you for pointing out the error in the naming, as well as that I could remove that second line. :) Definitely still treading the waters with Python, but I'm enjoying it immensely.
ArrantSquid
+1  A: 

There is usually more than one way that fulfills the specification, but often only one correct way. This is in fact the central design principle of Python (as opposed to, say, Perl). In your example, when you need key–value pairs instead of only keys or only values, use iteritems.

Philipp