Using toolz.pipe with methods

404 Views Asked by At

I have a string that I want to clean using pipe from toolz. But it seems I can't figure out how to apply the str.replace method in the pipeline. Here is an example:

x = '9\xa0766'

from toolz import pipe
import unidecode

# Can do like this, but don't want to use nesting.
int(unidecode.unidecode(x).replace(" ", ""))


# Wan't to try to do like this, with sequence of steps, applying transformations on previous output.
pipe(x, 
  unidecode.unidecode, 
  replace(" ", ""), 
  int
) # DON'T WORK!! 
# NameError: name 'replace' is not defined

More generally, notice that the output of unidecode.unidecode is a string. So I want to be able to apply some string methods to it.

pipe(x, 
  unidecode.unidecode, 
  type
)  # str

Is it possible with pipe?

2

There are 2 best solutions below

0
eriknw On

Yes, this is possible with toolz.pipe. Although you can use a lambda, I would use operator.methodcaller as so:

import operator as op
import unidecode
from toolz import pipe

x = '9\xa0766'

# Can do like this, but don't want to use nesting.
int(unidecode.unidecode(x).replace(" ", ""))

# Wan't to try to do like this, with sequence of steps, applying transformations on previous output.
pipe(
    x,
    unidecode.unidecode,
    op.methodcaller("replace", " ", ""),
    int
)
0
GRag On

You could also do the same in slightly different way using lambda

import unidecode
from toolz import pipe

x = '9\xa0766'


pipe(
    x,
    unidecode.unidecode,
    lambda x: x.replace(" ", ""),
    int
)

You could also make it into a function to reuse it elsewhere

import unidecode
from toolz import pipe, compose_left

x = '9\xa0766'

# this becomes a function that can be called
converter = compose_left(
    unidecode.unidecode,
    lambda x: x.replace(" ", ""),
    int
)


result = converter(x)

print(result)
#9766