Monday, December 20, 2010

[Level 2] Refactoring your single python file program into module files.

How to refactory your single pyhon file with multi module files?

1. create folder for modules.
2. create empty __init__.py in the folder.
3. move partial your code into the new folder.
4. add import syntax into your main program.
5. test it.
6. done.

e.g.
Before refactoring:
$ cat ./t.py
#!/usr/bin/python
class a():
  def a(self):
    print "call a()"

class b():
  def b(self):
    print "call b()"

if __name__ == '__main__':
  c=a()
  c.a()
  d=b()
  d.b()

After refactoring:
$ ls -al
total 8
drwxr-xr-x   5 root  root  170 Dec 20 23:14 .
drwxrwxrwt  16 root     root  544 Dec 20 23:17 ..
drwxr-xr-x   6 root  root  204 Dec 20 23:13 a
drwxr-xr-x   6 root  root  204 Dec 20 23:13 b
-rwxr--r--   1 root  root  119 Dec 20 23:14 t.py
$
$ ls a
__init__.py    __init__.pyc    a.py        a.pyc
$
$ ls b
__init__.py    __init__.pyc    b.py        b.pyc
$
$ cat ./t.py
#!/usr/bin/python
from a.a import a
from b.b import b
if __name__ == '__main__':
  c=a()
  c.a()
  d=b()
  d.b()
$
$ cat ./a/a.py
class a():
  def a(self):
    print "call a()"
$
$ cat ./b/b.py
class b():
  def b(self):
    print "call b()"
$


Wish this helps.
regards,
Stanley Huang