Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aliasing str.join in python

Is it possible to alias str.join in python3 ?

For example:

a=['a','b','c']
j=str.join
''.j(a)

but also to be able to do

' '.j(a)

with the same alias or more generally to be able to use it like:

string_here.j(iterable here)
like image 355
Mite Ristovski Avatar asked Dec 05 '25 15:12

Mite Ristovski


2 Answers

Not quite with the syntax you want, but close enough:

>>> a=['a','b','c']
>>> j=str.join
>>> j('', a)
'abc'
>>> j(' ', a)
'a b c'

str.join is an unbound method. To apply it to an object, you need to specify that object as the first argument.

like image 110
Remy Blank Avatar answered Dec 07 '25 05:12

Remy Blank


TL;DR: Yes, but not in the way you expect.

In your example, you are aliasing an unbound function. What that means simply is that is has no object to apply it on implicitly, so you have to pass on a reference to which object the operations are to be performed on.

This is what the self argument in methods is for. Normally you have it automatically passed for you when you use the `. style notation, but here you have to provide it explicitly.

>>> list_ = [1, 2, 3]
>>> f = str.join   # aliasing the class method
>>> f(' ', list_)  # passing a reference to s
prints "1 2 3"
>>> f('', list_ )  # flexibility to use any string

If you want to be able to just say f(list_), then the f function has to be bound. This means you have to know what string you're going to be using in advance. Here's how to do that:

>>> str_ = ' '
>>> list_ 
>>> f = str_.join   # aliasing the object method
>>> f(list_)        # no need to pass a reference now
"1 2 3"

I hope you understood what I was saying. Python is a great language and has the least gotcha's of any language. I couldn't FGITW my way into the top, but I hope you will like the comprehensive example. If you have any questions, just ask me.

like image 35
Yatharth Agarwal Avatar answered Dec 07 '25 05:12

Yatharth Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!