Snippet to get all local classes from a module












3















I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?



import inspect

import my_module

my_module_class_names = [
name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
if clazz.__module__ == my_module.__name__
]




  • inspect.getmembers(my_module, inspect.isclass) gets any class members of my_module.


  • if clazz.__module__ == my_module.__name__ ensures that classes imported into my_module are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already imported other classes, and therefore the list had extraneous members.


Alternatively, from within my_module:



import inspect
import sys

def class_names() -> List[str]:
return [
name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clazz.__module__ == sys.modules[__name__].__name__
]









share|improve this question





























    3















    I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?



    import inspect

    import my_module

    my_module_class_names = [
    name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
    if clazz.__module__ == my_module.__name__
    ]




    • inspect.getmembers(my_module, inspect.isclass) gets any class members of my_module.


    • if clazz.__module__ == my_module.__name__ ensures that classes imported into my_module are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already imported other classes, and therefore the list had extraneous members.


    Alternatively, from within my_module:



    import inspect
    import sys

    def class_names() -> List[str]:
    return [
    name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
    if clazz.__module__ == sys.modules[__name__].__name__
    ]









    share|improve this question



























      3












      3








      3








      I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?



      import inspect

      import my_module

      my_module_class_names = [
      name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
      if clazz.__module__ == my_module.__name__
      ]




      • inspect.getmembers(my_module, inspect.isclass) gets any class members of my_module.


      • if clazz.__module__ == my_module.__name__ ensures that classes imported into my_module are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already imported other classes, and therefore the list had extraneous members.


      Alternatively, from within my_module:



      import inspect
      import sys

      def class_names() -> List[str]:
      return [
      name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
      if clazz.__module__ == sys.modules[__name__].__name__
      ]









      share|improve this question
















      I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?



      import inspect

      import my_module

      my_module_class_names = [
      name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
      if clazz.__module__ == my_module.__name__
      ]




      • inspect.getmembers(my_module, inspect.isclass) gets any class members of my_module.


      • if clazz.__module__ == my_module.__name__ ensures that classes imported into my_module are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had already imported other classes, and therefore the list had extraneous members.


      Alternatively, from within my_module:



      import inspect
      import sys

      def class_names() -> List[str]:
      return [
      name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
      if clazz.__module__ == sys.modules[__name__].__name__
      ]






      python object-oriented python-3.x reflection modules






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 days ago









      200_success

      129k15152414




      129k15152414










      asked 2 days ago









      l0b0l0b0

      4,244923




      4,244923






















          1 Answer
          1






          active

          oldest

          votes


















          3














          I have already used similar code and it looks rather fine. Some nitpicks:




          • I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;

          • I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);


          • sys.modules[__name__].__name__ should be just __name__.




          Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:



          [cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]


          or



          my_module.CommonBase.__subclasses__()


          if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.






          share|improve this answer


























          • Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

            – l0b0
            yesterday













          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211235%2fsnippet-to-get-all-local-classes-from-a-module%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          I have already used similar code and it looks rather fine. Some nitpicks:




          • I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;

          • I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);


          • sys.modules[__name__].__name__ should be just __name__.




          Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:



          [cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]


          or



          my_module.CommonBase.__subclasses__()


          if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.






          share|improve this answer


























          • Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

            – l0b0
            yesterday


















          3














          I have already used similar code and it looks rather fine. Some nitpicks:




          • I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;

          • I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);


          • sys.modules[__name__].__name__ should be just __name__.




          Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:



          [cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]


          or



          my_module.CommonBase.__subclasses__()


          if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.






          share|improve this answer


























          • Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

            – l0b0
            yesterday
















          3












          3








          3







          I have already used similar code and it looks rather fine. Some nitpicks:




          • I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;

          • I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);


          • sys.modules[__name__].__name__ should be just __name__.




          Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:



          [cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]


          or



          my_module.CommonBase.__subclasses__()


          if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.






          share|improve this answer















          I have already used similar code and it looks rather fine. Some nitpicks:




          • I’d name the variable cls to mimic the name often used as first parameters of @classmethods; or class_ as it is more common;

          • I’d store a list of classes intead of a list of names, this feels more directly usable (and names are still stored as cls.__name__ if need be);


          • sys.modules[__name__].__name__ should be just __name__.




          Alternatively, since these classes seems related to each other, you may have an inheritance tree; or maybe a common base class. In this case, you could be even more specific using something such as:



          [cls for _, cls in inspect.getmembers(my_module, inspect.isclass) if issubclass(cls, my_module.CommonBase)]


          or



          my_module.CommonBase.__subclasses__()


          if there really is a single level of inheritance, but I wouldn't count much on it as it can break so easily.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited yesterday

























          answered yesterday









          Mathias EttingerMathias Ettinger

          23.9k33182




          23.9k33182













          • Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

            – l0b0
            yesterday





















          • Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

            – l0b0
            yesterday



















          Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

          – l0b0
          yesterday







          Excellent! I do need the actual class names rather than the types, and I don't have a class hierarchy, but this can serve as basically a recipe for anyone who wants either variant of this pattern.

          – l0b0
          yesterday




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211235%2fsnippet-to-get-all-local-classes-from-a-module%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Список кардиналов, возведённых папой римским Каликстом III

          Deduzione

          Mysql.sock missing - “Can't connect to local MySQL server through socket”