Search code examples
pythonsyntaxidentifier

How to call a method with spaces in the name?


I have the following class:

Help on class A in module a:

class A(__builtin__.object)
 |  Methods defined here:
 |  
 |  any vegetable(self)
 |      TODO document this
 |  
 |  getHeight(self)
 |      uses the chicken to measure it

Calling any vegetable doesn't work:

>>> a.A().any vegetable()
  File "<stdin>", line 1
    a.A().any vegetable()
                      ^
SyntaxError: invalid syntax

How can I call any vegetable?


Okay, I can't believe I have to provide more proof but here goes.

>>> dir(a.A)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'any vegetable', 'getHeight']

This isn't my class, so please don't tell me to rewrite it. I just need to call the method.


Solution

  • Use getattr:

    >>> a = A()
    >>> getattr(a, 'any vegetable')()
    

    Note that having names with weird characters such as spaces in them is a very, very bad idea. No sane person would ever do this.