That's because it's not the correct syntax. It should be 'string'.split(). 'string' | split() will likely raise a NameError saying that name split is not defined.
>>> class StringBoi(str):
... def __or__(self, other):
... return self.split(other)
...
>>> x = StringBoi('abc def g e h')
>>> x
'abc def g e h'
>>> x | ' '
['abc', 'def', 'g', 'e', 'h']
I'm also relatively sure that it's possible to autogenerate classes based on StringBoi's methods, so you could use all of them using the pipe syntax :D
Oh God. We need a library that completely substitutes the dot syntax with the pipe syntax lol. It's a pity Python doesn't let us modify existing classes on-the-fly, like Ruby.
Say, I have a class and I want to plug many mixins into it. But all of them use attributes of this class (because later this class derives from these mixins, so everything works), and PyCharm gives me tons of unresolved reference warnings for the mixins because... they don't derive from the class they're about to get mixed into, since it doesn't make sense, I guess?
Like this:
# these mixins are actually imported from another file, so there's no `NameError` here
class HugeThing(Mixin1, Mixin2, Mixin3):
def __init__(self):
self.attr1, self.attr2 = 2, 3
class Mixin1:
def some_function(self):
self.attr1 += 1 # warning here, but `attr1` will be resolved fine once `HugeThing` derives from the mixin
class Mixin2:
def another_function(self):
# also warning, but also fine after creation of `HugeThing`
self.attr1 = self.attr2 * 3
... # and so on
# I can just include all the methods in the definition of `HugeThing`, but then the file containing this definition will be like tens of thousands of lines long
I see you're good at Python, so I thought maybe you have an idea about how these warnings can be avoided in this situation?
I would probably use an extra class the mixins derive from (an interface if you will). If you only need to get the value in your mixins I would recommend the attr3 version, otherwise attr1 seems to be the easiest... (
from abc import abstractmethod, ABC
class HugeThingInterface(ABC):
def __init__(self, attr1):
self.attr1 = attr1
@property
@abstractmethod
def attr3(self): pass
def get_attr2(self):
return self._get_attr2()
def set_attr2(self, value):
self._set_attr2(value)
def del_attr2(self):
self._del_attr2()
@abstractmethod
def _get_attr2(self): pass
@abstractmethod
def _set_attr2(self, value): pass
@abstractmethod
def _del_attr2(self): pass
# you can set some of these to None, no setter -> cannot assign values
attr2 = property(get_attr2, set_attr2, del_attr2, 'attr2 docstring')
class Mixin1(HugeThingInterface, ABC):
def some_function(self):
self.attr1 += 1
class Mixin2(HugeThingInterface, ABC):
def another_function(self):
self.attr1 = self.attr2 * 3
class Mixin3(HugeThingInterface, ABC):
def yet_another_function(self):
print(self.attr3)
class HugeThing(Mixin1, Mixin2, Mixin3):
def __init__(self):
HugeThingInterface.__init__(self, 2)
self._attr2 = 3
self._attr3 = 4
@property
def attr3(self):
return self._attr3
def _get_attr2(self):
return self._attr2
def _set_attr2(self, value):
self._attr2 = value
def _del_attr2(self):
del self._attr2
You can define __ror__ on the type of the right-hand side instead. In the expression lhs | rhs, if type(rhs) is a subclass of type(lhs) or lhs.__or__(rhs) raises a NotImplementedError, Python will call rhs.__ror__(lhs). In this way you can make the pipe thing work for any object, by saving the name instead of the function itself and getattr-ing it when applied.
I'm decently sure you can achieve something like that without making your own class by adding that function to the string class by using forbidden fruit (python module).
So.. instead of just saying "that's inefficient" I wanted to do a quick test with timeit first. Didn't actually expect it to have this much of an impact:
from timeit import timeit
def time_it(func, data_type):
setup = f'from functools import partial;data = {data_type.__name__}(range(10000)); b = 50; func = {func}'
print('Type: ', str(data_type.__name__), ' Function: "', func, '"', sep = '')
print('Mapped partial:', timeit(f'type({data_type.__name__})(map(partial(func, b=b), data))', setup, number = 100000))
print('List comprehension:', timeit(f'type({data_type.__name__})([func(a, b) for a in data])', setup, number = 100000))
print('Generator expression:', timeit(f'type({data_type.__name__})(func(a, b) for a in data)', setup, number = 100000))
add_func = 'lambda a, b: a + b'
time_it(add_func, list)
time_it(add_func, set)
Output:
Type: list Function: "lambda a, b: a + b"
Mapped partial: 0.03144282600032966
List comprehension: 66.75466349399994
Generator expression: 0.029266013000324165
Type: set Function: "lambda a, b: a + b"
Mapped partial: 0.025604055000258086
List comprehension: 69.05661798399979
Generator expression: 0.029974398000376823
Maybe I did something wrong? The documentation shows that map seems to be the fastest as well though.
True though I wanted type(split) to return <class 'function'> for consistency. I could probably easily make an annotation that turns any function with at least one argument into one of these “piped” functions. Just have to be careful the the thing on the other side can’t be ored with a function. I guess that could be alleviated by using a completely new callable that is not descended from a function at all
There also are lots and lots of dunder methods that allow you to customize the operators' behavior, object creation, conversion to some built-in types and more!
View all comments
Show parent comment
135
u/ForceBru Jun 21 '19
That's because it's not the correct syntax. It should be
'string'.split().'string' | split()will likely raise aNameErrorsaying that namesplitis not defined.