4

I'm using SQLAlchemy and am trying to import the function group_by into the interpreter, but I can't seem to find it. Is there an easy way to search the module tree to see where this function lives?

Of course I've tried from sqlalchemy import + tab and searching manually, but at each tree level there are too many options to check.

jclancy
  • 49,598
  • 5
  • 30
  • 34

2 Answers2

4

The easy way to do this is to step outside the interpreter and just search the docs.


Meanwhile, it looks to me like there is no such function to import. There are group_by methods on sqlalchemy.orm.query.Query and sqlalchemy.sql.expression.[Compound]Select[Base] objects.


But if you really want to recursively walk through all the modules in a package looking for a name, here's how you'd do it:

import inspect

def find_name(package, name):
    if hasattr(package, name):
        yield package
    for modulename, submodule in inspect.getmembers(package, inspect.ismodule):
        yield from find_name(submodule, name)

For Python 3.2 or earlier, you need to replace the yield from with a loop:

for modulename, submodule in inspect.getmembers(package, inspect.ismodule):
    for result in find_name(submodule, name):
        yield result

And if you just want the first result, instead of all results, you can just return instead of yielding:

def find_name(package, name):
    if hasattr(package, name):
        return package
    for modulename, submodule in inspect.getmembers(package, inspect.ismodule):
        result = find_name(submodule, name)
        if result:
            return result
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Huh. I could have sworn I tried statements using it as a method and it said there was no such function. This is good to know, but I'd still like an answer to the module-searching question. – jclancy May 17 '13 at 20:31
  • Is it possible that you tried using it on the wrong kind of object? – abarnert May 17 '13 at 20:35
0

try printing SQLAlchemy.__all__ which will return you a list of all functions in that module which are publicly available.

abhishekgarg
  • 1,480
  • 9
  • 14
  • Right, this is almost exactly the same as `from sqlalchemy import + tab`, it just leaves out submodules. – jclancy May 17 '13 at 20:25
  • there is a thread with same kind of topic [http://stackoverflow.com/questions/139180/listing-all-functions-in-a-python-module] – abhishekgarg May 17 '13 at 20:27