Return a module spec based on a file location. To indicate that the module is a package, set submodule_search_locations to a list of directory paths. An empty list is sufficient, though its not otherwise useful to the import system. The loader must take a spec as its only __in
(name, location=None, *, loader=None,
submodule_search_locations=_POPULATE)
| 546 | |
| 547 | |
| 548 | def spec_from_file_location(name, location=None, *, loader=None, |
| 549 | submodule_search_locations=_POPULATE): |
| 550 | """Return a module spec based on a file location. |
| 551 | |
| 552 | To indicate that the module is a package, set |
| 553 | submodule_search_locations to a list of directory paths. An |
| 554 | empty list is sufficient, though its not otherwise useful to the |
| 555 | import system. |
| 556 | |
| 557 | The loader must take a spec as its only __init__() arg. |
| 558 | |
| 559 | """ |
| 560 | if location is None: |
| 561 | # The caller may simply want a partially populated location- |
| 562 | # oriented spec. So we set the location to a bogus value and |
| 563 | # fill in as much as we can. |
| 564 | location = '<unknown>' |
| 565 | if hasattr(loader, 'get_filename'): |
| 566 | # ExecutionLoader |
| 567 | try: |
| 568 | location = loader.get_filename(name) |
| 569 | except ImportError: |
| 570 | pass |
| 571 | else: |
| 572 | location = _os.fspath(location) |
| 573 | try: |
| 574 | location = _path_abspath(location) |
| 575 | except OSError: |
| 576 | pass |
| 577 | |
| 578 | # If the location is on the filesystem, but doesn't actually exist, |
| 579 | # we could return None here, indicating that the location is not |
| 580 | # valid. However, we don't have a good way of testing since an |
| 581 | # indirect location (e.g. a zip file or URL) will look like a |
| 582 | # non-existent file relative to the filesystem. |
| 583 | |
| 584 | spec = _bootstrap.ModuleSpec(name, loader, origin=location) |
| 585 | spec._set_fileattr = True |
| 586 | |
| 587 | # Pick a loader if one wasn't provided. |
| 588 | if loader is None: |
| 589 | for loader_class, suffixes in _get_supported_file_loaders(): |
| 590 | if location.endswith(tuple(suffixes)): |
| 591 | loader = loader_class(name, location) |
| 592 | spec.loader = loader |
| 593 | break |
| 594 | else: |
| 595 | return None |
| 596 | |
| 597 | # Set submodule_search_paths appropriately. |
| 598 | if submodule_search_locations is _POPULATE: |
| 599 | # Check the loader. |
| 600 | if hasattr(loader, 'is_package'): |
| 601 | try: |
| 602 | is_package = loader.is_package(name) |
| 603 | except ImportError: |
| 604 | pass |
| 605 | else: |
searching dependent graphs…