Monday 15 February 2010

object - Making a class act as string in Python when you have both str and unicode -



object - Making a class act as string in Python when you have both str and unicode -

disclaimer: using python 2.6 lot of weird reasons. is.

i'm trying create object deed string properties this:

class setting(str): def __new__(cls, value, source): homecoming super(setting, cls).__new__(cls, value) def __init__(self, value, source): self.value = value self.source = source

this works rather nicely. scarily nice. ;)

but: need back upwards both unicode , str objects. ideally extend basestring. unfortunately, logical reasons; changing super class basestring not work , gives error:

typeerror: basestring type cannot instantiated

anyone have thought how go fixing this? thanks. :)

ok, sorry code horrible, hard understand, subclassing builtin (like str, file) bad idea, in production code.

what recommend generic approach, create class 2 variables , override special operators desired result (ie create deed str):

class setting: def __init__(self, value, source): self.value = value self.source = source def __add__(self, rhs): #keeping object immutable homecoming setting(self.value + rhs, self.source)

however in interests of extreme python code, cannot think of single utilize case (there improve way), here workaround:

class setting(object): def __new__(cls, value, source): #pick right base of operations class base_class = str if isinstance(value, str) else unicode #construct new setting class right base of operations new_type = type(cls.__name__, (base_class,), dict(cls.__dict__)) homecoming base_class.__new__(new_type, value) def __init__(self, value, source): self.value = value self.source = source

the thought dynamically create class right base of operations based on type of value given. yes, should more scary , shouldn't utilize it. alter base of operations became whatever class type 'value' was, thought more readable.

the reason couldn't utilize basestring abstract class, or @ to the lowest degree acts one. when did:

return super(setting, cls).__new__(cls, value)

it tried create current instance of setting new instance of basestring, since abstract means has no implementation, nil call.

python object unicode subclass

No comments:

Post a Comment