Ticket #15351: fix_import_statements.patch

File fix_import_statements.patch, 5.5 KB (added by Vincent Delecroix, 9 years ago)
  • sage/misc/dev_tools.py

    # HG changeset patch
    # User Vincent Delecroix <20100.delecroix@gmail.com>
    # Date 1383521231 18000
    # Node ID 2a83c1c8d7abd73d95b91e80a437de03f8d91d78
    # Parent  7c97a70b162921d91dca8c6c9cd792ea98dcfaec
    trac: 15351
    fix import_statements.
    
    diff --git a/sage/misc/dev_tools.py b/sage/misc/dev_tools.py
    a b def runsnake(command): 
    8181    cProfile.runctx(preparse(command.lstrip().rstrip()), get_main_globals(), locals(), filename=tmpfile)
    8282    os.system("/usr/bin/python -E `which runsnake` %s &"%tmpfile)
    8383
    84 def print_import_statement(module, name, lazy):
     84def print_or_update(string, data):
     85    r"""
     86    if ``data`` is ``None`` then print the string otherwise append ``string`` to
     87    the data.
     88    """
     89    if data is None:
     90        print string
     91    else:
     92        data.append(string)
     93
     94def print_import_statement(module, name, lazy, answer=None):
    8595    r"""
    8696    Print an import statement.
    8797
    def print_import_statement(module, name, 
    101111        lazy_import('sage.misc.dev_tools', 'print_import_statement')
    102112    """
    103113    if lazy:
    104         print "lazy_import('%s', '%s')"%(module, name)
     114        print_or_update("lazy_import('%s', '%s')"%(module, name), answer)
    105115    else:
    106         print "from %s import %s"%(module, name)
     116        print_or_update("from %s import %s"%(module, name), answer)
    107117
    108118def import_statements(*objects, **options):
    109119    """
    def import_statements(*objects, **option 
    119129    - ``verbose`` -- a boolean (default: ``True``)
    120130      Whether to print information in case of ambiguity.
    121131
     132    - ``answer_as_str`` -- a boolean (default: ``False``)
     133      If ``True`` return a string instead of printing the statement.
     134
    122135    EXAMPLES::
    123136
    124137        sage: import_statements(WeylGroup, lazy_attribute)
    def import_statements(*objects, **option 
    211224    from sage.misc.flatten import flatten
    212225    from sage.misc.lazy_import import LazyImport
    213226
     227    answer_as_str = options.get("answer_as_str",False)
     228    if answer_as_str:
     229        answer = []
     230    else:
     231        answer = None
     232
    214233    lazy = options.get("lazy", False)
    215234    verbose = options.get("verbose", True)
    216235    if lazy:
    217         print "from sage.misc.lazy_import import lazy_import"
     236        print_or_update("from sage.misc.lazy_import import lazy_import", answer)
    218237
    219238    for obj in objects:
    220239        # if obj is a string use it has a name and look for an object
    def import_statements(*objects, **option 
    238257        # Case 1: the object is a module
    239258        if inspect.ismodule(obj):
    240259            if lazy:
    241                 print "lazy_import('%s')"%obj.__name__
     260                print_or_update("lazy_import('%s')"%obj.__name__, answer)
    242261            else:
    243                 print "import %s"%obj.__name__
     262                print_or_update("import %s"%obj.__name__, answer)
    244263            continue
    245264
    246265        # Case 2: the object is defined in its module
    def import_statements(*objects, **option 
    252271
    253272        if module:
    254273            d = sys.modules[module].__dict__
     274            names = None
    255275            if name is None:
    256276                names = sorted(key for key in d if d[key] is obj)
    257             else:
     277            elif name in d:
    258278                names = [name]
    259279            if names:
    260280                if verbose and len(names) > 1:
    261281                    print "  ** Warning **: several names for that object: %s"%', '.join(names)
    262                 print_import_statement(module, names[0], lazy)
     282                print_import_statement(module, names[0], lazy, answer)
    263283                continue
    264284
    265285
    def import_statements(*objects, **option 
    271291
    272292                if name is not None:
    273293                    if name in d and d[name] is obj:
    274                         names[module] = name
     294                        names[module] = [name]
    275295                else:
    276296                    n = [key for key in d if d[key] is obj]
    277297                    if n:
    def import_statements(*objects, **option 
    311331            name = names[module][0]
    312332
    313333        if name is not None:
    314             print_import_statement(module, name, lazy)
     334            print_import_statement(module, name, lazy, answer)
    315335        else:
    316336            raise ValueError("no import statement for %s"%obj)
     337
     338    if answer is not None:
     339        return '\n'.join(answer)
     340
     341def which_import_statements_fail():
     342    r"""
     343    Run import statements on *all* objects and print the one for which the
     344    import fails or return "from sage.all import my_object".
     345
     346    The returne value is a couple of lists. The first one corresponds to the
     347    import_statements that answer "from sage.all import XXX" and the second
     348    corresponds to the list of import_statements that fail.
     349
     350    TESTS::
     351
     352        sage: from sage.misc.devtools import which_import_statements_fail
     353        sage: sage_all, errors = which_import_statements_fail() # we get some warnings
     354        ...
     355        sage: errors          # good
     356        ['maxima_calculus']
     357        sage: len(sage_all)   # bad
     358        63
     359    """
     360    import sage.all
     361    errors = []
     362    sage_all = []
     363    for name in sage.all.__dict__.iterkeys():
     364        try:
     365            to_test = import_statements(name, answer_as_str=True)
     366        except ValueError:
     367            errors.append(name)
     368            continue
     369
     370        if to_test.startswith('from sage.all import'):
     371            sage_all.append(name)
     372            continue
     373        try:
     374            exec import_statements(name, answer_as_str=True)
     375        except ImportError:
     376            errors.append(name)
     377    return sage_all, errors