[Python] Is it possible to create groups/layers in method chaining in Python?

Discussão em 'Python' iniciado por Stack, Janeiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I am aware that I can use method chaining by simply having methods return self, e.g.

    object.routine1().routine2().routine3()


    But is it possible to organize methods into layers or groups when applying method chaining? e.g.

    object.Layer1.routine1().routine2().Layer2.routine3()


    The context is that I am trying to build a text analytics pipeline and the different layers would correspond to text level, sentence level and token level preprocessing steps. So what I am trying to build is something like this

    text = "This is an example foo text with some special characters!!!! And some sentences"

    pr = TextPreprocessor(text)
    processed_text = (
    pr.text_level.lower_case()
    .sentence_level.split_sentences().remove_special_characters()
    .token_level.tokenize()
    .text
    )


    This is the code that almost (!) gets the text processing example to work:

    import re

    class TextLevelPreprocessor:
    def __init__(self, parent):
    self.parent = parent

    def lower_case(self):
    self.parent.text = self.parent.text.lower()
    return self.parent

    class SentenceLevelPreprocessor:
    def __init__(self, parent):
    self.parent = parent

    def split_sentences(self):
    self.parent.text = self.parent.text.split('. ')
    return self.parent

    def remove_special_characters(self):
    self.parent.text = [re.sub('[!@#$]', '', s) for s in self.parent.text]
    return self.parent

    class TokenLevelPreprocessor:
    def __init__(self, parent):
    self.parent = parent

    def tokenize(self):
    self.parent.text = [t.split() for t in self.parent.text]
    return self.parent

    class TextPreprocessor:
    def __init__(self, text):
    self.text = text
    self.text_level = TextLevelPreprocessor(self)
    self.sentence_level = SentenceLevelPreprocessor(self)
    self.token_level = TokenLevelPreprocessor(self)


    However here only this syntax would work

    pr = TextPreprocessor(text)
    processed_text = (
    pr.text_level.lower_case()
    .sentence_level.split_sentences().
    .sentence_level.remove_special_characters()
    .token_level.tokenize()
    .text
    )


    which would mean that one would have to add the "Layer" or "Group" everytime one uses a method, which seems verbose.

    Continue reading...

Compartilhe esta Página