views:

81

answers:

1

This is more of a curiosity question than anything else. I'm new with Python and playing around with it. I've just looked at the base64 module. What if instead of doing:

import base64
string = 'Foo Bar'
encoded = base664.b64encode

I wanted to do something like:

>>> class b64string():
>>>   <something>
>>>
>>> string = b64string('Foo Bar')
>>> string
'Foo Bar'
>>> string.encode64()
'Rm9vIEJhcg=='
>>> string
'Rm9vIEJhcg=='
>>> string.assign('QmFyIEZvbw==')
>>> string
'QmFyIEZvbw=='
>>> string.b64decode()
'Bar Foo'
>>> string
'Bar Foo'

Is there a simple, pythonic way to create that class?

I've begun with this:

>>> class b64string(base64):
...   def __init__(self, v):
...     self.value=v

And already I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    module.__init__() takes at most 2 arguments (3 given)

And don't get me started on (just to see what would happen):

>>> class b64string(str, base64): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

I know how to do it manually by listing all of the attributes of base64 in a new class and calling them with the stored value as argument. But is there a neat, pythonic way to do this? Is it a bad idea to do it? The idea would be, if needed, to do it with many such modules and have "super strings" that would have as modules all the things I would need to do with them. Is that bad? Is it un-pythonic? If it is pythonic, how is it done?

+1  A: 

I don't think creating such complex string-like classes is a good idea, but if you really want to, here's a simple snippet that runs your examples.

First, we define a class that's a generic string-wrapper. Its core is a __getattr__ function that forwards every method call to a given self.module, adding self.string as the first parameter and remembering the result on self.string.

import base64

class ModuledString(object):
    def __init__(self, string):
        self.string = string

    def __getattr__(self, attrname):
        def func(*args, **kwargs):
            result = getattr(self.module, attrname)(self.string, *args, **kwargs)
            self.string = result
            return result
        return func

    def __str__(self):
        return str(self.string)

Creating a string-wrapper with base64 capabilities is then easy:

class B64String(ModuledString):
    module = base64

if __name__ == '__main__':
    string = B64String('Foo Bar')
    print string
    # 'Foo Bar'
    print string.b64encode()
    # 'Rm9vIEJhcg=='
    print string
    # 'Rm9vIEJhcg=='
    string.string = 'QmFyIEZvbw=='
    print string
    # 'QmFyIEZvbw=='
    print string.b64decode()
    # 'Bar Foo'

Note that the above examples work only because b64encode and b64decode take a string as the first argument and return a string as the result (there is no validation in my __getattr__ function). A random function from some random module would probably raise some kind of exception. So, after all, it would be better to restrict the usage to a predefined set of functions from a given module, but it should be easy now.

I repeat, I don't recommend using such code in any serious project, only for fun.

DzinX
Thanks! (And sorry for the late response.) This is HUGELY useful, not for any actual code, of course, bur for understanding how Python works and how it ought to be used best. I would have thought that a generic wrapper would have been overkill, and there are many other things I would have considered under a very different angle. This was just the thing I needed. Brilliant!
eje211