Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Redundancy in Python

I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy:

First thing are imports: They all look something like

import Class from Class

from class import Class

And the second thing are __init__ methods:

__init__(self,arg1,...,argn):
    self.arg1 = arg1
    ...
    self.argn = argn

Are there ways to avoid these duplications?

like image 218
Jasper Avatar asked Jan 27 '11 09:01

Jasper


3 Answers

The second thing is not redundancy - it is setting instance attributes. You can do it also like this:

class Foo:

   def __init__(self, **kwargs):
       for name, value in kwargs.items():
          setattr(self, name, value)

But then you need to call Foo like this:

   Foo(arg1=1, arg2=2, arg3=3)

Also your import seems to have improper syntax. It should be from Class import Class. This looks redundant to you, because it seems, that you are storing each class in a separate file (module) - and that is exactly redundant. Python is not Java, you should usually hold more objects in one module. Keep in mind, that module itself is an object. Also you should name modules properly - the default code style guide says that modules should be all lowercase with no special chars. Like re or urllib for example.

like image 66
gruszczy Avatar answered Nov 18 '22 08:11

gruszczy


from module import Class

It is common for class names to be different from their containing module's name. If you have just one class per module with an identical name, consider moving that class up a level in your hierarchy.

def __init__(self, a, b, c):
  self.a = a
  self.b = b
  self.c = c

This does often seem to be kinda annoying, but it's really not bad, readability-wise, compared to alternatives. However, if you have a lot of parameters that you merely assign as attributes with no other work in your init, then consider inheriting from a namedtuple or similar, which can generate such boilerplate for you. (Namedtuple in particular has other ramifications and will only be sometimes suitable. I'm using it as an example of a base class which can handle this type of boilerplate.)

like image 2
Fred Nurk Avatar answered Nov 18 '22 08:11

Fred Nurk


Version for args:

class Foo:

   def __init__(self, *args):
       for index,arg in enumerate(args):
          setattr(self, 'arg%s'%index, arg)


Foo(1,2,3)
>>> Foo.arg0
1
like image 1
Frost.baka Avatar answered Nov 18 '22 09:11

Frost.baka