Base.Chop API rationale

Base.chop

chop(s::AbstractString; head::Integer = 0, tail::Integer = 1)

Remove the first head and the last tail characters from s. The call chop(s) removes the last character from s. If it is requested to remove more characters than length(s) then an empty string is returned.

I am curious about the reasoning for two choices:

  • uses keyword arguments instead of positional
  • defaults to tail=1

Especially the default tail=1 I really am puzzled by: what is this function for?

See the discussion in julia#17457 and #17922: apparently this function was copied from the Perl chop function and originally only removed one character from the end, before additional head and tail arguments were eventually added by julia#24126 (later converted to keywords). Even then there was some contention about how useful this function is, and there are still discussions about improving the API (#37397).

5 Likes

Ruby also has String#chop.

2 Likes

This was an unfortunate oversight when the head keyword was added. The default should definitely not be tail=1 when a value is passed for head. We might even be able to change that in a minor release with a deprecation since it seems so bad. The way would be to deprecate passing a head value without also passing a tail value and then later changing the default.

5 Likes