Python: accessing another class of the current module by name

I have the following setup in one module:

class A(object):
    # stuff

class B(object):
    # stuff

Now what I want to do is create an instance of the class Aby name (I just have the class name as a string) inside B. How can I do this while avoiding function globals?

+3
source share
3 answers

Why not just use it A? Or do you have a string 'A'? If so, globals()['A']this is the way to go. An alternative would be getattr(sys.modules[__name__], 'A'), but obviously globals()more appropriate.

>>> dis.dis(lambda: getattr(sys.modules[__name__], 'Foo'))
  1           0 LOAD_GLOBAL              0 (getattr)
              3 LOAD_GLOBAL              1 (sys)
              6 LOAD_ATTR                2 (modules)
              9 LOAD_GLOBAL              3 (__name__)
             12 BINARY_SUBSCR
             13 LOAD_CONST               1 ('Foo')
             16 CALL_FUNCTION            2
             19 RETURN_VALUE

>>> dis.dis(lambda: globals()['Foo'])
  1           0 LOAD_GLOBAL              0 (globals)
              3 CALL_FUNCTION            0
              6 LOAD_CONST               1 ('Foo')
              9 BINARY_SUBSCR
             10 RETURN_VALUE

>>> dis.dis(lambda: Foo)
  1           0 LOAD_GLOBAL              0 (Foo)
              3 RETURN_VALUE

So, just by looking at the instructions used for the various ways to access Foo, the use globals()is likely faster than through sys.modules.

+6
source

, :

  • ,

    ...
    connection-type: FooConnection
    ...
    
  • class FooConnection(Connection): ...
    class BarConnection(Connection): ...
    class BazConnection(Connection): ...
    
  • "FooConnection" FooConnection.


, :

  • connection-type: Foo
    

    , .

  • :

    implementations = {
        "Foo": FooConnection,
        "Bar": BarConnection,
        "Baz": BazConnection
    }
    

    , , . . .

  • , .


, . , , , globals; , , , . .

+3

I don’t understand what you mean by “accessing class A by name,” but there are usually three main approaches, depending on what you really want to do.

  • You create an instance of class A inside class B __init__
  • You inherit class A in class B
  • What posted by @ThiefMaster.
+2
source

All Articles