helper function in a class' namespace

Stargaming stargaming at gmail.com
Thu Jan 31 21:05:44 CET 2008


On Thu, 31 Jan 2008 20:51:23 +0100, Helmut Jarausch wrote:

> Hi,
> 
> the following code works fine
> 
> def Helper(M) :
>    return 'H>'+M

String concatenation is generally considered unpythonic, better use 
string interpolation::

    'H> %s' % (M,)

> class A(object):
>    def __init__(self,Msg) :
>      print Helper(Msg)
> 
> B=A('ZZ')

Watch out your names -- they could confuse other Python programmers 
introspecting your namespaces! Names bound to objects should generally be 
lowercase (argument ``msg``, object ``b``, argument ``m``, function 
``helper``). For details on what the Python community has agreed on is 
"good style," see the `Style Guide <http://www.python.org/dev/peps/
pep-0008/>`_.

> but the Helper function is in the module's namespace.

Where's the problem? If it is "I don't want Helper to be visible", just 
use this convention: "Names beginning with an underscore are private. 
Better keep your fingers off."

> I'd like to put it into class A's namespace. Note, the Helper function
> doesn't need access to any instance attributes.
> 
> The first variant
> 
> class A(object):
>    def Helper(M) :
>      return 'H>'+M
>    def __init__(self,Msg) :
>      print Helper(Msg)
> 
> doesn't work since Python is looking for a global function Helper (why?)

Because in the scope of the ``__init__`` function, the name ``Helper`` is 
not bound. It then jumps out to the global scope.

> The alternative
> 
> class A(object):
>    def Helper(M) :
>      return 'H>'+M
>    def __init__(self,Msg) :
>      print A.Helper(Msg)
> 
> doesn't work either since now the first argument to A.Helper must be
> 'A'.
> 
> So, isn't it possible to have a helper function in the namespace of a
> class without (the overhead of) passing a 'self' or a 'cls' parameter?

Of course it is! You can decorate certain functions with the 
`staticmethod <http://docs.python.org/lib/built-in-funcs.html#l2h-69>`_ 
wrapper, which will do exactly what you wanted::

    class A(object):
        @staticmethod
        def helper(m):
            return 'H>%s' % (m,)
        def __init__(self, msg):
            print A.helper(msg) # or self.helper


HTH,



More information about the Python-list mailing list