0

I created a class to store settings for TF-IDF matrices generation.

class TFIDF_settings:
    max_features = 5000
    
    class word_level(TFIDF_settings):
        analyzer = "word"
        ngram_range = (1,1)
    
    class ngram_level(TFIDF_settings):
        analyzer = "word"
        ngram_range = (2,3)

I would like the attribute TFIDF_settings.max_feature to be smoothly passed to all of the inner classes - print(TFIDF_settings.word_level.max_features) should return 5000.

As you can see in the code, I thought that inheriting the outer class will do the job, but it throws an NameError.

<ipython-input-18-0ddd9158decc> in TFIDF_settings()
      2     max_features = 5000
      3 
----> 4     class word_level(TFIDF_settings):
      5         analyzer = "word"
      6         ngram_range = (1,1)

NameError: name 'TFIDF_settings' is not defined

Is there any way to (preferrably implicitly) pass the max_features attribute of the outer class to the inner classes?

matwasilewski
  • 384
  • 2
  • 11
  • I don't think this is possible. The outer class name isn't defined until you get to the end of the `class` block, so you can't refer to it when defining the inner classes. – Barmar Jul 25 '21 at 11:50
  • [Can a Python inner class be a subclass of its own outer class?](https://stackoverflow.com/questions/39077623/can-a-python-inner-class-be-a-subclass-of-its-own-outer-class) – Guy Jul 25 '21 at 11:50
  • 1
    Why do they need to be nested classes instead of top-level subclasses? – Barmar Jul 25 '21 at 11:52
  • @Barmar I could make them subclasses, but I thought that enforcing the syntax `TFIDF_settings.word_level.*` would make the code clearer by making it explicit that word_level etc. are different configurations for TFIDF generation. In other words, all configuration should be nested within TFIDF_settings and easily viewable in an IDE. – matwasilewski Jul 25 '21 at 12:02
  • 1
    Seems like a "XY question". Your question is answered by what Guy linked above. If you'd describe what you want to achieve with that instead, it would perhaps help. Also note that you're jumping between classes and instances, which isn't really helpful. – Ulrich Eckhardt Jul 25 '21 at 12:03

0 Answers0