avatar Bite 309. A simple document class

When we want to transform our data often, method chaining is a wonderful paradigm that allows us to write elegant and less error-prone code.

For example, given a string s, we can do the following in Python s.strip().lower().split().

When working with databases, we often have code snippets like the next one:

  filter(Engineer.id == Employee.id).\
  filter(Employee.name == 'dilbert').\

Implementing method chaining is not hard, although there are at least two different ways of achieving this functionality.

Now it's your turn to try it out.


In this Bite you are asked to implement a simple document class that can be used to create text documents.

For this Bite, a document is a list of strings, each string representing exactly one line.

The order in the list is the order of the document. Indices start at 0.

However, because working with documents basically means a lot of repeated function calls, you want to provide at least some convenience by offering method chaining.

Be aware that there are (at least) two ways to achieve method chaining and you can choose which one you want to implement here. Both will pass the tests.

With method chaining it is easy to execute multiple transformations of a document at once:

d = (
  .add_line("My first sentence.")
  .add_line("My second sentence.")
  .add_line("Introduction", 0)
>>> Introduction
>>> My first sentence. My second sentence
>>> 2
>>> 7
>>> ['first', 'introduction', 'my', 'second', 'sentence']

We provided you with a skeleton of a Document class that offers typical methods for manipulating documents. 

For this bite, we only consider methods that change whole lines, which makes things a lot easier.

Feel free to add more methods to your liking.

If you wonder why there is no method for undoing the last action, stay tuned for another Bite!

Happy coding.

Login and get coding
go back Intermediate level
Bitecoin 3X

14 out of 15 users completed this Bite.
Will you be Pythonista #15 to crack this Bite?
Resolution time: ~78 min. (avg. submissions of 5-240 min.)

We use Python 3.8