Blog of


APyTA_03 : Python syntax and conventions

APyTA_03 : Python syntax and conventions

Ok, let's start from a typical function to apprehend the syntax :

def doSomethingSpecial(_GivenThis,_GivenThat):
    """ This function adds given parameters if they have the same type """
    ListOfArgument = [_GivenThis,_GivenThat]
    for currentArgument in ListOfArgument:
        #Printing each argument to be sure:

    if type(_GivenThis) == type(_GivenThat):
        myResult = _GivenThis+_GivenThat
        return myResult
        return "ERROR, conflicting types"

print doSomethingSpecial(1,2)
#1 2 3
print doSomethingSpecial("a","b")
#a b ab
print doSomethingSpecial("a",2)
#a 2 ERROR, conflicting types

So, let's analyze these points:

1) NO BRACES. All python blocks of instructions are created and closed by indentation.
Do not forget the first ':', which will force you to create an additional indent.
Be really sure to setup your current editor with a rule like: Tabulations ARE four spaces.
Forget about Maya script editor and install Eclipse, or NotePad++.

2) def allow you to define a function.
In my Naming conventions, a function start always by a VERB.
Because a function is always an ACTION, it does something.
If you can't nameit that way, you are probally in the wrong path.

3) NO TYPES ??? Yes, python is strongly typed, we will see that later.
But you don't need to tell him what kind of data is your variable.
Python will know that. So you don't need that.
Quite useful ! you can also re-use a variable with a different content.
Please notice that is the case for the return value.
It is a string, but other contexts the function will return an int or a float !

4) A list of variables in python are written with [], comma separated,
and can be iterate very lightly with a for in statement.
Notice also the name of the variable, the first letter in Majuscule
to better isolate different parts in one name.

5) Document your code ! # is the commenting tag to tell python
that the next characters on the line are NOT code.
Usefull to comment, but notice the triple-double quote at the start of our function.
This is a DOCSTRING. On header of a function or a class, I advice you to always describe
your function goal and return behaviour, with algorithm and tweaks if any.

Note: This capacity of python to cast on the fly the type of your variable
will give you a very powerful tool: polymorphism.
You can make a function working with integers as well as float, or manage multi-types of return values.
But (there is always a but), forbid yourself to have one same variable
and re-use its name to store several things at different time.
The name of the variable must be as precise as you can, and stay genuine.
Of course you can have a variable "mySelectedObject" (who can be a Mesh, a Camera, etc...)

Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.