[Tutor] How to reuse code in Python

Kent Johnson kent37 at tds.net
Tue Nov 29 13:57:17 CET 2005


Negroup - wrote:
> 2005/11/29, Kent Johnson <kent37 at tds.net>:
>>class A:
>>  def __init__(self, limit):
>>    self.limit = limit
>>    self.num = 20
>>  def info(self):
>>    return self.limit
>>  def inc_num(self):
>>    self.num += 1
>>  def check(self):
>>    return self.num > self.limit
>>
>>Now you can create whatever kind of A's you want:
>>from module import A
>>a = A(30)
>>etc.
> 
> 
> This is true. However following this approach I have touched the code
> in module.py (the original), and I'd avoid to do that.

Why? It was not written to be reusable, now you are trying to reuse it. A minor rewrite now will save you trouble later.

If you want to be backwards compatible you can give a default value for limit:
class A:
  def __init__(self, limit=25):
  # etc

then you can say
a = A()
a.info() --> 25

b = A(30)
b.info() --> 30

a.info() --> still 25

 
> A way I found is to import module directly and then simply assign to
> it the property limit:
> 
>>>>import module
>>>>module.limit = 25
>>>>a = module.A()
>>>>b = module.A()
> 
> (25, 25)
> 
> This however has a side effect (that luckily is not a big problem,
> because I don't need to change limit after the first time):
> 
>>>>module.limit = 26
>>>>a.info(), b.info()
> 
> (26, 26)

Yes, you can do that but it's ugly and fragile. It will cause obscure bugs the first time you write a program that uses module twice with two different limits. Maybe you will never do that. I prefer not to put time bombs in my code.
> 
> 
>>>where is the value 30 coming from?
>>
>>from module.limit.
> 
> 
> I have some difficulties understanding this. In my previous post the
> syntax is: from module import A and so 'module' is not imported.

Right, but all access to limit is from inside module. Names are looked up first in the local namespace (the current function), then in any enclosing name space (if you have nested functions), then in the namespace of the *containing* module (*not* the module where the function is used, rather the module where it is defined) and finally in the built-in namespace.

Again, 'global' scope is the scope of the textually containing module, not the scope of the calling module. This is called static or lexical scoping. See the tutorial and WikiPedia for more:
http://docs.python.org/tut/node11.html#SECTION0011200000000000000000
http://en.wikipedia.org/wiki/Static_scoping

Kent


-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list