[Tutor] Declaring methods in modules.

Steven D'Aprano steve at pearwood.info
Sun Apr 11 18:37:15 CEST 2010

On Sun, 11 Apr 2010 10:30:54 pm Ray Parrish wrote:
> Hello,
> I am working on some stuff, and I would like to be able to write a
> module which can be imported, and after it's been imported I would
> like to be able to access it's functions as methods.
> In other words, if I do the import of module ISPdetector, I want to
> then be able to make calls like the following -
>     ipAddress = ""
>     emails = ipAddress.GetEmailAddresses()

Can't be done -- in Python, built-in types like strings can't have new 
methods added to them, and thank goodness for that! The ability to 
monkey-patch builtins is more dangerous than useful. 

But you can subclass builtins, as Alan suggested:

# module ISPdetector
class MyString(string):
    def GetEmailAddresses(self):

# another module
import ISPdetector
ipAddress = ISPdetector.MyString("")
emails = ipAddress.GetEmailAddresses()

But that is a strange API design. IP addresses aren't strings, they're 
integers, and although they are commonly written in quad-dotted form as 
a string, you don't want to treat them as strings. For example, 
something like ipAddress.replace('2', 'P') makes no sense.

Also, making GetEmailAddresses a method of an IP address implies that 
address *have* email addresses, which is nonsense. People have email 
addresses. Computer accounts have email addresses. Particular email 
*messages* come from an IP address, but IP addresses don't have email 
addresses. A better name would be ipaddress.find_email_from().

So I would suggest the best API is either to create an IP address class 
(or better still, don't re-invent the wheel, use one of the fine 
existing IP address modules already written), or write functions in the 
module and just call them:

import ISPdetector
ipAddress = ""
emails = find_email_from(ipAddress)

Remember, in Python methods are just syntactic sugar for function calls. 
obj.method(arg) is just another way of spelling method(obj, arg).

Steven D'Aprano

More information about the Tutor mailing list