Search code examples
pythonpyramidpython-import

Is it possible to import a class defined inside a function?


There is a class from a 3rd party system that I'd like to sub-class for my own purposes, but it's defined within a function, like so:

def foo():
    class Bar():

    return Bar

If I try to import it just with from x import bar, I get ImportError: cannot import name 'Bar'. Is it possible (or wise) to import Bar? Perhaps the original coder put the class inside the function specifically to prevent others from using it directly?

The class I'm trying to get is CookieSession, defined inside BaseCookieSessionFactory, which can be found here: http://docs.pylonsproject.org/projects/pyramid/en/master/_modules/pyramid/session.html

It already does 90% of what I want, and it seems like it would be a waste to implement my own from scratch, since I would just be copy-pasting much of the code.

Edit: Following the advice in Chepner's answer, I sub-classed it by building my own factory function:

from pyramid.session import SignedCookieSessionFactory

def MySessionFactory(secret, [other args here...]):
    @implementer(ISession)
    class MySession(SignedCookieSessionFactory(secret)):
       ...
    return MySession

Solution

  • You can't import it, because it doesn't exist until foo is actually called. However, it appears that foo simply defines the function and returns a reference to it. In that case, you just need something like

    from otherfile import foo
    Bar = foo()
    
    x = Bar()  # create an instance of Bar