Close
Community Post

Python Tips'N'Tricks #3

>>PART 2<<

 

Local/Modules

Handling functionality you would like to have everywhere in your project or component can be quite a hassle from time to time.So, what if I told you that there is a special place in every component called modules?

When reading about module on demand there is quite an interresting line hidden just at the end:

The current component is searched first.
If the DAT is not found, the local/modules component of the current component is then searched.
Next the local/modules component of each parent is successively searched.
If the DAT is still not found, None is returned.
This means, that we can simply place a DAT in a local/modules folder and import it on the same or every lower level then the specific component using either the import (and the import from ) or the mod keyword.
This way we can implement helper-functions without them cluttering our component functionality or, when having many instances of a component with an extension, not having to reinit/replacing them without having to rely on cloning.
For example, placing your extensioncode in local/modules you can now place the following line in the Extension Object paramater, indipendant of the level your are in.
mod.NamOfDat.NameOfClass(me)

Another example is defining helper-functions. For example this dat with the name nodelayout has the following code

def layout_row( list_of_nodes ):
	first_node = list_of_nodes[0]
	offset = first_node.nodeWidth * 1.1
	for index, node in enumerate( list_of_nodes ):
		node.nodeX = first_node.nodeX + offset * index
 
def layout_column( list_of_nodes ):
	first_node = list_of_nodes[0]
	offset = first_node.nodeHeight * 1.1
	for index, node in enumerate( list_of_nodes ):
		node.nodeY = first_node.nodeY + offset * index

Now, in any DAT I can use the import statement

import nodelayout
 
nodelayout.layout_row( parent().findChildren() )

 

MORE COMPREHENSIONS

Everyone already knows about list-comprehensions

children = [ operator for operator in parent().findChildren() ]

But, you can also create other data-structures!

my_dictionary = { operator.name : operator for operator in parent().findChildren() }
my_set = { operator for operator in parent().findChildren() }

 

SETS

Sets are a a datastructure most people do not know about. Contrary to lists, dicts and tuples they are an unordered collection of items. This means you cannot acces any item in a set directly. Also, every item can exist only once per set. But why then?

Well, for one, they are super easy to compare! Comparing two lists or touples heavily relies on the order of elements, even though the elements themself are the same.

list_a = [1,2,3]
list_b = [1,3,2]
debug( list_a == list_b ) #will return False
 
set_a = set( list_a )
set_b = set( list_b )
debug( set_a == set_b ) #will return True

Also, checking if an element exists in a list can be quite computational expensive, where using the in operator in a set is much less demanding. Nice.

Next step, removing an element from a list also relies on knowing the position of an element. With sets, you can simply substract one set of another. And the best part? No error if it does not exists!

set_a = {1,3,2}
#remove 2 from the set
set_b = set_a - {2} 
#set_b -&gt; {1,3}
 
#remove non existing element
set_c = set_a - {3, 34}
#set_c -&gt; {1,2}
 
#or use .remove(value) to muatte the set directly!

To access the members you now need to use a simple for loop.

Better for-loops

For-Loops aper super awsome and easy to use. When using lists you get the item, and with dicts you get the key. But what if we do not want to know the index of our current item or we do not want to acces the dict-member via the key? Enter enumerate, items, values, keys!

my_dict = { "a" : "Foo", "b" : "Bar" }
 
# :( 
for key in my_dict:
	debug( key, my_dict[key] )
 
# :)
for key, value in my_dict.items():
	debug(key, value)
 
for key in my_dict.keys():
	debug(key)
 
for value in my_dict.values():
	debug(value)

And for lists, instead of having to use a seperate index-variable, we can simply use the enumerate method!

my_list = ["Foo", "Bar", None, 3]
 
index = 0
for element in my_list:
	debug( index, element )
	index += 1
 
for index, element in enumerate( my_list ):
	debug( index, element )

 

Dict Update

Sometimes you want to add new values to a dictionary and override already existing ones. Using the update() function you can mutate a dictionary with new values

dict_a = { 	"foo" : "bar", 
			"hello" : "world" }
 
dict_b = {  "foo" : "BAR",
			"res" : "frank" }
 
dict_a.update( dict_b )
debug( dict_a )
#prints {'foo': 'BAR', 'hello': 'world', 'res': 'frank'} 

 

Comments