make a class instance from a string ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bo Yang

    make a class instance from a string ?

    Hi,
    I know in java , we can use

    class.ForName(" classname")


    to get an instance of the class 'classname' from a
    string , in python , how do I do that ?

    Thanks in advance !

  • bearophileHUGS@lycos.com

    #2
    Re: make a class instance from a string ?

    Bo Yang:[color=blue]
    > to get an instance of the class 'classname' from a
    > string , in python , how do I do that ?[/color]

    This is a possibile way:

    class C: pass
    c = locals()["C"]()
    print c

    Bye,
    bearophile

    Comment

    • Diez B. Roggisch

      #3
      Re: make a class instance from a string ?

      Bo Yang wrote:
      [color=blue]
      > Hi,
      > I know in java , we can use
      >
      > class.ForName(" classname")
      >
      >
      > to get an instance of the class 'classname' from a
      > string , in python , how do I do that ?[/color]

      You can use

      getattr(module, classname)(*arg uments)


      Diez


      Comment

      • Luke Plant

        #4
        Re: make a class instance from a string ?

        Bo Yang wrote:
        [color=blue]
        > I know in java , we can use
        >
        > class.ForName(" classname")
        >
        >
        > to get an instance of the class 'classname' from a
        > string , in python , how do I do that ?[/color]

        In Python, classes are first class objects, so normally you would pass
        the class itself around, rather than use the names of classes. Of
        course that might not be practical or applicable in your situation.

        Luke

        Comment

        • Diez B. Roggisch

          #5
          Re: make a class instance from a string ?

          Luke Plant wrote:
          [color=blue]
          > Bo Yang wrote:
          >[color=green]
          >> I know in java , we can use
          >>
          >> class.ForName(" classname")
          >>
          >>
          >> to get an instance of the class 'classname' from a
          >> string , in python , how do I do that ?[/color]
          >
          > In Python, classes are first class objects, so normally you would pass
          > the class itself around, rather than use the names of classes. Of
          > course that might not be practical or applicable in your situation.[/color]

          While JAVA is severely limited regarding the number of seats in the first
          class, classes _are_ sitting there.

          The need for dynamic attribute look up is even more frequent in python -
          think getattr, __getitem__, __getattr__.

          Diez

          Comment

          • Terry Hancock

            #6
            Re: make a class instance from a string ?

            On 23 Feb 2006 05:22:25 -0800
            "Luke Plant" <luke.plant@gma il.com> wrote:[color=blue]
            > In Python, classes are first class objects, so normally
            > you would pass the class itself around, rather than use
            > the names of classes. Of course that might not be
            > practical or applicable in your situation.[/color]

            It is in fact, a particular source of annoyance when the
            object is meant to be serialized to disk with pickle or
            the like, and especially when it is an extension object.

            A good idiom for "look me up in the source code after you
            unpack me" is required. I think some things like ZODB
            will already do that for you, but it seems basic enough
            that there ought to be a general approved method of doing
            that in Python -- you know, "one obvious way".

            --
            Terry Hancock (hancock@Anansi Spaceworks.com)
            Anansi Spaceworks http://www.AnansiSpaceworks.com

            Comment

            • Mike Woodhouse

              #7
              Re: make a class instance from a string ?

              Is there anything particularly bad with

              obj = eval(classname + "()")

              ?

              It appears to work, but I'm a noobie so I could be missing something
              nasty, in which any edication would be gratefully received.

              Mike

              Comment

              • Scott David Daniels

                #8
                Re: make a class instance from a string ?

                Mike Woodhouse wrote:[color=blue]
                > Is there anything particularly bad with
                > obj = eval(classname + "()")
                > It appears to work, but I'm a noobie so I could be missing something
                > nasty, in which any edication would be gratefully received.[/color]

                It is a little too indirect. Usually wanting to use "eval" or "exec"
                means your code is probably not properly structured (a "code smell").
                You can pass classes around as values; you typically needn't work with
                their names. If the name comes from outside, a dictionary of names to
                classes means you can re-implement your code without being tightly
                coupled to your I/O formats. If you still want to use the name
                I'd go with:
                globals()[classname]()
                over eval, but it is your code.

                Here's a danger to think about:
                Suppose your source of class names has:
                '__import__(os) .system("delete critical.file") '
                for a class name?


                --Scott David Daniels
                scott.daniels@a cm.org

                Comment

                • Steven D'Aprano

                  #9
                  Re: make a class instance from a string ?

                  On Fri, 24 Feb 2006 06:37:27 -0800, Mike Woodhouse wrote:
                  [color=blue]
                  > Is there anything particularly bad with
                  >
                  > obj = eval(classname + "()")
                  >
                  > ?
                  >
                  > It appears to work, but I'm a noobie so I could be missing something
                  > nasty, in which any edication would be gratefully received.[/color]

                  In your own code, that you control? Nothing particularly bad.

                  In your public web application, using classname supplied by some anonymous
                  remote user? It could be bad:

                  obj = eval("(lambda : os.system('ls') )" + "()")

                  only, instead of 'ls', imagine a more... serious shell command.

                  Using eval is like running a small piece of Python code. If you control
                  the code (or to be precise, the expression) then it is no more dangerous
                  than any other code you choose to run.

                  On the other hand, if you give access to your system to anonymous users,
                  you have to assume some of them will be malicious, and they will be a lot
                  more inventive searching for security holes than you.


                  --
                  Steven.

                  Comment

                  • Méta-MCI

                    #10
                    Re: make a class instance from a string ?

                    Hi!

                    Perso, I like this...

                    MCI


                    Comment

                    Working...