kreativitea
kreativitea

Reputation: 1791

Passing 'argument lists' as a namedtuple in python

I created a namedtuple called Engine that holds most of the information I want to pass around my program. Inside of this tuple, are a couple of parameters and two instanced classes that are used by methods downstream.

Engine = namedtuple('Engine', 'website, browser, s, e')
engine = Engine(website, browser, s(), e())

i have a function, download(engine) that I pass engine into. Subfunctions in download pass engine-- some of them use website, some of them use browser, some of them use s, and some use e.

Now, the cognitive overhead (of me as a programmer) goes down considerably, I no longer have to ensure that argument lists are up to date both downstream and upstream of a particular change that might happen-- I just pass engine downstream, and if I use an argument in a method, i use engine.foo.

On the other, it feels like this is 'lazy' programming-- just wrapping everything up into an engine 'class' and having the variables as methods on the class seems to make everything almost too easy. Further, I'd swear that there was some kind of overhead I'm not seeing with this implementation. Is there any kind of precedent to this, cause it feels too useful to ignore.

Should I be using namedtuples as replacement for arguments throughout my program to reduce the number of arguments that get passed?

Upvotes: 1

Views: 3494

Answers (2)

Lukas Graf
Lukas Graf

Reputation: 32590

I'd say this is actually a very good pattern. namedtuples are extremely efficient and increase readability a lot. Their space overhead compared to regular tuples is effectively zero.

So namedtuples could be seen as kind of lightweight classes, and can be grown into them if their responsibilities increase.

Raymond Hettinger explains their advantages and use cases in quite some detail in this Talk from PyCon US 2011 [11:35 - 26:00], much better than I ever could.

Upvotes: 5

Krumelur
Krumelur

Reputation: 32497

It sounds like some variant of a parameter object pattern. On the other hand, it sounds like you could implement it as a class as well, i.e.

class Engine(object):
   website = ...
   browser = ...
   s = ...
   e = ...

   def download(self):
       ...
   def _sub_function(self):
       ...

Upvotes: 4

Related Questions