Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namedTuples definition across multiple chained functions

I am currently building a modular pipeline of functions to process some data in Python (2.7).

I'm sticking to a loosely functional style, without any objects (for the type of code and the routines I'm applying its making perfect sense and the code so far is neat and readable, designing objects would just make everything a bit more obfuscated).

To keep things consistent, I've defined a custom namedtuple, with field names etc. The idea is that the initial function reads some data files and returns one of these specially defined tuples. The following functions will read it, work with the data fields and return a new tuple (since they are immutable) with the alterations. However, I can't seem to avoid having to do the import collections and redefine the custom type - See the code example.

import collections
def NewFunction(MyCustomType):

    a = ...
    b = ...

    MyCustomType = collections.namedtuple('MyCustomType', 'a, b')
    return MyCustomType(a, b)

It's not really causing a problem, but I am curious as if there isn't a more "global" way to do it without so much repetition. And if there is, isn't the way I'm doing more "side-effect free" aka functional?? (Sorry for actually two questions here: the first a practical closed python question and the second a more open/philosophical question.)

Thanks in advance!

like image 844
S. Diaxo Avatar asked Jul 04 '13 18:07

S. Diaxo


1 Answers

The namedtuple() function is basically a class factory. Build that class once at the module level:

import collections

MyCustomType = collections.namedtuple('MyCustomType', 'a, b')

then import MyCustomType everywhere instead. It's just a class, you don't have to re-create that class every time you want to build the tuple.

import somemodule

def NewFunction(param):

    a = ...
    b = ...

    return somemodule.MyCustomType(a, b)
like image 75
Martijn Pieters Avatar answered Oct 22 '22 02:10

Martijn Pieters