Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a one-off or anonymous class in Python?

I frequently have simple classes which I'll only ever want a single instance of. As a simple example:

import datetime
import sys

class PS1(object):
    def __repr__(self):
        now = datetime.datetime.now()
        return str(now.strftime("%H:%M:%S"))

sys.ps1 = PS1()

Is there a way that I could somehow combine the definition and instantiation into a single step and achieve the same results?

As another example, just as something that is simple enough to understand.

class Example(object):
    def methodOne(self, a, b):
        return a + b

    def methodTwo(self, a, b):
        return a * b

example = Example()

I googled around and found nothing (lots of people throwing around the words one-off and anonymous but nobody seems to be talking about the same thing I am). I tried this, but it didn't work:

example = class(object):
    def methodOne(self, a, b):
        return a + b

    def methodTwo(self, a, b):
        return a * b

I realize I don't gain much, just one line I don't have to type plus one fewer things in my namespace, so I understand if this doesn't exist.

like image 320
ArtOfWarfare Avatar asked Jul 22 '14 18:07

ArtOfWarfare


1 Answers

I think you don't see this often because it's really hard to read, but ...

sys.ps1 = type('PS1', (object,), {'__repr__': lambda self: datetime.datetime.now().strftime('%H:%M:%S')})()

would do the trick here...

I use type to dynmically create a class (the arguments are name, base classes, class dictionary). The class dictionary just consists of a single function __repr__ in this case.

Hopefully we can agree that the full format is much easier to grok and use ;-).

like image 154
mgilson Avatar answered Sep 21 '22 02:09

mgilson