You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

890 lines
29 KiB

Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
Make importlib.abc.SourceLoader the primary mechanism for importlib. This required moving the class from importlib/abc.py into importlib/_bootstrap.py and jiggering some code to work better with the class. This included changing how the file finder worked to better meet import semantics. This also led to fixing importlib to handle the empty string from sys.path as import currently does (and making me wish we didn't support that instead just required people to insert '.' instead to represent cwd). It also required making the new set_data abstractmethod create any needed subdirectories implicitly thanks to __pycache__ (it was either this or grow the SourceLoader ABC to gain an 'exists' method and either a mkdir method or have set_data with no data arg mean to create a directory). Lastly, as an optimization the file loaders cache the file path where the finder found something to use for loading (this is thanks to having a sourceless loader separate from the source loader to simplify the code and cut out stat calls). Unfortunately test_runpy assumed a loader would always work for a module, even if you changed from underneath it what it was expected to work with. By simply dropping the previous loader in test_runpy so the proper loader can be returned by the finder fixed the failure. At this point importlib deviates from import on two points: 1. The exception raised when trying to import a file is different (import does an explicit file check to print a special message, importlib just says the path cannot be imported as if it was just some module name). 2. the co_filename on a code object is not being set to where bytecode was actually loaded from instead of where the marshalled code object originally came from (a solution for this has already been agreed upon on python-dev but has not been implemented yet; issue8611).
16 years ago
  1. """Core implementation of import.
  2. This module is NOT meant to be directly imported! It has been designed such
  3. that it can be bootstrapped into Python as the implementation of import. As
  4. such it requires the injection of specific modules and attributes in order to
  5. work. One should use importlib as the public-facing version of this module.
  6. """
  7. # Injected modules are '_warnings', 'imp', 'sys', 'marshal', 'errno', '_io',
  8. # and '_os' (a.k.a. 'posix', 'nt' or 'os2').
  9. # Injected attribute is path_sep.
  10. #
  11. # When editing this code be aware that code executed at import time CANNOT
  12. # reference any injected objects! This includes not only global code but also
  13. # anything specified at the class level.
  14. # Bootstrap-related code ######################################################
  15. # XXX Could also expose Modules/getpath.c:joinpath()
  16. def _path_join(*args):
  17. """Replacement for os.path.join."""
  18. return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
  19. for x in args if x)
  20. def _path_exists(path):
  21. """Replacement for os.path.exists."""
  22. try:
  23. _os.stat(path)
  24. except OSError:
  25. return False
  26. else:
  27. return True
  28. def _path_is_mode_type(path, mode):
  29. """Test whether the path is the specified mode type."""
  30. try:
  31. stat_info = _os.stat(path)
  32. except OSError:
  33. return False
  34. return (stat_info.st_mode & 0o170000) == mode
  35. # XXX Could also expose Modules/getpath.c:isfile()
  36. def _path_isfile(path):
  37. """Replacement for os.path.isfile."""
  38. return _path_is_mode_type(path, 0o100000)
  39. # XXX Could also expose Modules/getpath.c:isdir()
  40. def _path_isdir(path):
  41. """Replacement for os.path.isdir."""
  42. if not path:
  43. path = _os.getcwd()
  44. return _path_is_mode_type(path, 0o040000)
  45. def _path_without_ext(path, ext_type):
  46. """Replacement for os.path.splitext()[0]."""
  47. for suffix in _suffix_list(ext_type):
  48. if path.endswith(suffix):
  49. return path[:-len(suffix)]
  50. else:
  51. raise ValueError("path is not of the specified type")
  52. def _path_absolute(path):
  53. """Replacement for os.path.abspath."""
  54. if not path:
  55. path = _os.getcwd()
  56. try:
  57. return _os._getfullpathname(path)
  58. except AttributeError:
  59. if path.startswith('/'):
  60. return path
  61. else:
  62. return _path_join(_os.getcwd(), path)
  63. def _wrap(new, old):
  64. """Simple substitute for functools.wraps."""
  65. for replace in ['__module__', '__name__', '__doc__']:
  66. setattr(new, replace, getattr(old, replace))
  67. new.__dict__.update(old.__dict__)
  68. code_type = type(_wrap.__code__)
  69. # Finder/loader utility code ##################################################
  70. def set_package(fxn):
  71. """Set __package__ on the returned module."""
  72. def wrapper(*args, **kwargs):
  73. module = fxn(*args, **kwargs)
  74. if not hasattr(module, '__package__') or module.__package__ is None:
  75. module.__package__ = module.__name__
  76. if not hasattr(module, '__path__'):
  77. module.__package__ = module.__package__.rpartition('.')[0]
  78. return module
  79. _wrap(wrapper, fxn)
  80. return wrapper
  81. def set_loader(fxn):
  82. """Set __loader__ on the returned module."""
  83. def wrapper(self, *args, **kwargs):
  84. module = fxn(self, *args, **kwargs)
  85. if not hasattr(module, '__loader__'):
  86. module.__loader__ = self
  87. return module
  88. _wrap(wrapper, fxn)
  89. return wrapper
  90. def module_for_loader(fxn):
  91. """Decorator to handle selecting the proper module for loaders.
  92. The decorated function is passed the module to use instead of the module
  93. name. The module passed in to the function is either from sys.modules if
  94. it already exists or is a new module which has __name__ set and is inserted
  95. into sys.modules. If an exception is raised and the decorator created the
  96. module it is subsequently removed from sys.modules.
  97. The decorator assumes that the decorated function takes the module name as
  98. the second argument.
  99. """
  100. def decorated(self, fullname, *args, **kwargs):
  101. module = sys.modules.get(fullname)
  102. is_reload = bool(module)
  103. if not is_reload:
  104. # This must be done before open() is called as the 'io' module
  105. # implicitly imports 'locale' and would otherwise trigger an
  106. # infinite loop.
  107. module = imp.new_module(fullname)
  108. sys.modules[fullname] = module
  109. try:
  110. return fxn(self, module, *args, **kwargs)
  111. except:
  112. if not is_reload:
  113. del sys.modules[fullname]
  114. raise
  115. _wrap(decorated, fxn)
  116. return decorated
  117. def _check_name(method):
  118. """Decorator to verify that the module being requested matches the one the
  119. loader can handle.
  120. The first argument (self) must define _name which the second argument is
  121. compared against. If the comparison fails then ImportError is raised.
  122. """
  123. def inner(self, name, *args, **kwargs):
  124. if self._name != name:
  125. raise ImportError("loader cannot handle %s" % name)
  126. return method(self, name, *args, **kwargs)
  127. _wrap(inner, method)
  128. return inner
  129. def _requires_builtin(fxn):
  130. """Decorator to verify the named module is built-in."""
  131. def wrapper(self, fullname):
  132. if fullname not in sys.builtin_module_names:
  133. raise ImportError("{0} is not a built-in module".format(fullname))
  134. return fxn(self, fullname)
  135. _wrap(wrapper, fxn)
  136. return wrapper
  137. def _requires_frozen(fxn):
  138. """Decorator to verify the named module is frozen."""
  139. def wrapper(self, fullname):
  140. if not imp.is_frozen(fullname):
  141. raise ImportError("{0} is not a frozen module".format(fullname))
  142. return fxn(self, fullname)
  143. _wrap(wrapper, fxn)
  144. return wrapper
  145. def _suffix_list(suffix_type):
  146. """Return a list of file suffixes based on the imp file type."""
  147. return [suffix[0] for suffix in imp.get_suffixes()
  148. if suffix[2] == suffix_type]
  149. # Loaders #####################################################################
  150. class BuiltinImporter:
  151. """Meta path import for built-in modules.
  152. All methods are either class or static methods to avoid the need to
  153. instantiate the class.
  154. """
  155. @classmethod
  156. def find_module(cls, fullname, path=None):
  157. """Find the built-in module.
  158. If 'path' is ever specified then the search is considered a failure.
  159. """
  160. if path is not None:
  161. return None
  162. return cls if imp.is_builtin(fullname) else None
  163. @classmethod
  164. @set_package
  165. @set_loader
  166. @_requires_builtin
  167. def load_module(cls, fullname):
  168. """Load a built-in module."""
  169. is_reload = fullname in sys.modules
  170. try:
  171. return imp.init_builtin(fullname)
  172. except:
  173. if not is_reload and fullname in sys.modules:
  174. del sys.modules[fullname]
  175. raise
  176. @classmethod
  177. @_requires_builtin
  178. def get_code(cls, fullname):
  179. """Return None as built-in modules do not have code objects."""
  180. return None
  181. @classmethod
  182. @_requires_builtin
  183. def get_source(cls, fullname):
  184. """Return None as built-in modules do not have source code."""
  185. return None
  186. @classmethod
  187. @_requires_builtin
  188. def is_package(cls, fullname):
  189. """Return None as built-in module are never packages."""
  190. return False
  191. class FrozenImporter:
  192. """Meta path import for frozen modules.
  193. All methods are either class or static methods to avoid the need to
  194. instantiate the class.
  195. """
  196. @classmethod
  197. def find_module(cls, fullname, path=None):
  198. """Find a frozen module."""
  199. return cls if imp.is_frozen(fullname) else None
  200. @classmethod
  201. @set_package
  202. @set_loader
  203. @_requires_frozen
  204. def load_module(cls, fullname):
  205. """Load a frozen module."""
  206. is_reload = fullname in sys.modules
  207. try:
  208. return imp.init_frozen(fullname)
  209. except:
  210. if not is_reload and fullname in sys.modules:
  211. del sys.modules[fullname]
  212. raise
  213. @classmethod
  214. @_requires_frozen
  215. def get_code(cls, fullname):
  216. """Return the code object for the frozen module."""
  217. return imp.get_frozen_object(fullname)
  218. @classmethod
  219. @_requires_frozen
  220. def get_source(cls, fullname):
  221. """Return None as frozen modules do not have source code."""
  222. return None
  223. @classmethod
  224. @_requires_frozen
  225. def is_package(cls, fullname):
  226. """Return if the frozen module is a package."""
  227. return imp.is_frozen_package(fullname)
  228. class _LoaderBasics:
  229. """Base class of common code needed by both SourceLoader and
  230. _SourcelessFileLoader."""
  231. def is_package(self, fullname):
  232. """Concrete implementation of InspectLoader.is_package by checking if
  233. the path returned by get_filename has a filename of '__init__.py'."""
  234. filename = self.get_filename(fullname).rpartition(path_sep)[2]
  235. return filename.rsplit('.', 1)[0] == '__init__'
  236. def _bytes_from_bytecode(self, fullname, data, source_mtime):
  237. """Return the marshalled bytes from bytecode, verifying the magic
  238. number and timestamp along the way.
  239. If source_mtime is None then skip the timestamp check.
  240. """
  241. magic = data[:4]
  242. raw_timestamp = data[4:8]
  243. if len(magic) != 4 or magic != imp.get_magic():
  244. raise ImportError("bad magic number in {}".format(fullname))
  245. elif len(raw_timestamp) != 4:
  246. raise EOFError("bad timestamp in {}".format(fullname))
  247. elif source_mtime is not None:
  248. if marshal._r_long(raw_timestamp) != source_mtime:
  249. raise ImportError("bytecode is stale for {}".format(fullname))
  250. # Can't return the code object as errors from marshal loading need to
  251. # propagate even when source is available.
  252. return data[8:]
  253. @module_for_loader
  254. def _load_module(self, module, *, sourceless=False):
  255. """Helper for load_module able to handle either source or sourceless
  256. loading."""
  257. name = module.__name__
  258. code_object = self.get_code(name)
  259. module.__file__ = self.get_filename(name)
  260. if not sourceless:
  261. module.__cached__ = imp.cache_from_source(module.__file__)
  262. else:
  263. module.__cached__ = module.__file__
  264. module.__package__ = name
  265. if self.is_package(name):
  266. module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
  267. else:
  268. module.__package__ = module.__package__.rpartition('.')[0]
  269. module.__loader__ = self
  270. exec(code_object, module.__dict__)
  271. return module
  272. class SourceLoader(_LoaderBasics):
  273. def path_mtime(self, path):
  274. """Optional method that returns the modification time (an int) for the
  275. specified path, where path is a str.
  276. Implementing this method allows the loader to read bytecode files.
  277. """
  278. raise NotImplementedError
  279. def set_data(self, path, data):
  280. """Optional method which writes data (bytes) to a file path (a str).
  281. Implementing this method allows for the writing of bytecode files.
  282. """
  283. raise NotImplementedError
  284. def get_source(self, fullname):
  285. """Concrete implementation of InspectLoader.get_source."""
  286. import tokenize
  287. path = self.get_filename(fullname)
  288. try:
  289. source_bytes = self.get_data(path)
  290. except IOError:
  291. raise ImportError("source not available through get_data()")
  292. encoding = tokenize.detect_encoding(_io.BytesIO(source_bytes).readline)
  293. newline_decoder = _io.IncrementalNewlineDecoder(None, True)
  294. return newline_decoder.decode(source_bytes.decode(encoding[0]))
  295. def get_code(self, fullname):
  296. """Concrete implementation of InspectLoader.get_code.
  297. Reading of bytecode requires path_mtime to be implemented. To write
  298. bytecode, set_data must also be implemented.
  299. """
  300. source_path = self.get_filename(fullname)
  301. bytecode_path = imp.cache_from_source(source_path)
  302. source_mtime = None
  303. if bytecode_path is not None:
  304. try:
  305. source_mtime = self.path_mtime(source_path)
  306. except NotImplementedError:
  307. pass
  308. else:
  309. try:
  310. data = self.get_data(bytecode_path)
  311. except IOError:
  312. pass
  313. else:
  314. try:
  315. bytes_data = self._bytes_from_bytecode(fullname, data,
  316. source_mtime)
  317. except (ImportError, EOFError):
  318. pass
  319. else:
  320. found = marshal.loads(bytes_data)
  321. if isinstance(found, code_type):
  322. return found
  323. else:
  324. msg = "Non-code object in {}"
  325. raise ImportError(msg.format(bytecode_path))
  326. source_bytes = self.get_data(source_path)
  327. code_object = compile(source_bytes, source_path, 'exec',
  328. dont_inherit=True)
  329. if (not sys.dont_write_bytecode and bytecode_path is not None and
  330. source_mtime is not None):
  331. # If e.g. Jython ever implements imp.cache_from_source to have
  332. # their own cached file format, this block of code will most likely
  333. # throw an exception.
  334. data = bytearray(imp.get_magic())
  335. data.extend(marshal._w_long(source_mtime))
  336. data.extend(marshal.dumps(code_object))
  337. try:
  338. self.set_data(bytecode_path, data)
  339. except NotImplementedError:
  340. pass
  341. return code_object
  342. def load_module(self, fullname):
  343. """Concrete implementation of Loader.load_module.
  344. Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
  345. implemented to load source code. Use of bytecode is dictated by whether
  346. get_code uses/writes bytecode.
  347. """
  348. return self._load_module(fullname)
  349. class _FileLoader:
  350. """Base file loader class which implements the loader protocol methods that
  351. require file system usage."""
  352. def __init__(self, fullname, path):
  353. """Cache the module name and the path to the file found by the
  354. finder."""
  355. self._name = fullname
  356. self._path = path
  357. @_check_name
  358. def get_filename(self, fullname):
  359. """Return the path to the source file as found by the finder."""
  360. return self._path
  361. def get_data(self, path):
  362. """Return the data from path as raw bytes."""
  363. with _io.FileIO(path, 'r') as file:
  364. return file.read()
  365. class _SourceFileLoader(_FileLoader, SourceLoader):
  366. """Concrete implementation of SourceLoader using the file system."""
  367. def path_mtime(self, path):
  368. """Return the modification time for the path."""
  369. return int(_os.stat(path).st_mtime)
  370. def set_data(self, path, data):
  371. """Write bytes data to a file."""
  372. parent, _, filename = path.rpartition(path_sep)
  373. path_parts = []
  374. # Figure out what directories are missing.
  375. while parent and not _path_isdir(parent):
  376. parent, _, part = parent.rpartition(path_sep)
  377. path_parts.append(part)
  378. # Create needed directories.
  379. for part in reversed(path_parts):
  380. parent = _path_join(parent, part)
  381. try:
  382. _os.mkdir(parent)
  383. except OSError as exc:
  384. # Probably another Python process already created the dir.
  385. if exc.errno == errno.EEXIST:
  386. continue
  387. else:
  388. raise
  389. except IOError as exc:
  390. # If can't get proper access, then just forget about writing
  391. # the data.
  392. if exc.errno == errno.EACCES:
  393. return
  394. else:
  395. raise
  396. try:
  397. with _io.FileIO(path, 'wb') as file:
  398. file.write(data)
  399. except IOError as exc:
  400. # Don't worry if you can't write bytecode.
  401. if exc.errno == errno.EACCES:
  402. return
  403. else:
  404. raise
  405. class _SourcelessFileLoader(_FileLoader, _LoaderBasics):
  406. """Loader which handles sourceless file imports."""
  407. def load_module(self, fullname):
  408. return self._load_module(fullname, sourceless=True)
  409. def get_code(self, fullname):
  410. path = self.get_filename(fullname)
  411. data = self.get_data(path)
  412. bytes_data = self._bytes_from_bytecode(fullname, data, None)
  413. found = marshal.loads(bytes_data)
  414. if isinstance(found, code_type):
  415. return found
  416. else:
  417. raise ImportError("Non-code object in {}".format(path))
  418. def get_source(self, fullname):
  419. """Return None as there is no source code."""
  420. return None
  421. class _ExtensionFileLoader:
  422. """Loader for extension modules.
  423. The constructor is designed to work with FileFinder.
  424. """
  425. def __init__(self, name, path):
  426. """Initialize the loader.
  427. If is_pkg is True then an exception is raised as extension modules
  428. cannot be the __init__ module for an extension module.
  429. """
  430. self._name = name
  431. self._path = path
  432. @_check_name
  433. @set_package
  434. @set_loader
  435. def load_module(self, fullname):
  436. """Load an extension module."""
  437. is_reload = fullname in sys.modules
  438. try:
  439. return imp.load_dynamic(fullname, self._path)
  440. except:
  441. if not is_reload and fullname in sys.modules:
  442. del sys.modules[fullname]
  443. raise
  444. @_check_name
  445. def is_package(self, fullname):
  446. """Return False as an extension module can never be a package."""
  447. return False
  448. @_check_name
  449. def get_code(self, fullname):
  450. """Return None as an extension module cannot create a code object."""
  451. return None
  452. @_check_name
  453. def get_source(self, fullname):
  454. """Return None as extension modules have no source code."""
  455. return None
  456. # Finders #####################################################################
  457. class PathFinder:
  458. """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
  459. @classmethod
  460. def _path_hooks(cls, path, hooks=None):
  461. """Search sequence of hooks for a finder for 'path'.
  462. If 'hooks' is false then use sys.path_hooks.
  463. """
  464. if not hooks:
  465. hooks = sys.path_hooks
  466. for hook in hooks:
  467. try:
  468. return hook(path)
  469. except ImportError:
  470. continue
  471. else:
  472. raise ImportError("no path hook found for {0}".format(path))
  473. @classmethod
  474. def _path_importer_cache(cls, path, default=None):
  475. """Get the finder for the path from sys.path_importer_cache.
  476. If the path is not in the cache, find the appropriate finder and cache
  477. it. If None is cached, get the default finder and cache that
  478. (if applicable).
  479. Because of NullImporter, some finder should be returned. The only
  480. explicit fail case is if None is cached but the path cannot be used for
  481. the default hook, for which ImportError is raised.
  482. """
  483. try:
  484. finder = sys.path_importer_cache[path]
  485. except KeyError:
  486. finder = cls._path_hooks(path)
  487. sys.path_importer_cache[path] = finder
  488. else:
  489. if finder is None and default:
  490. # Raises ImportError on failure.
  491. finder = default(path)
  492. sys.path_importer_cache[path] = finder
  493. return finder
  494. @classmethod
  495. def find_module(cls, fullname, path=None):
  496. """Find the module on sys.path or 'path' based on sys.path_hooks and
  497. sys.path_importer_cache."""
  498. if not path:
  499. path = sys.path
  500. for entry in path:
  501. try:
  502. finder = cls._path_importer_cache(entry)
  503. except ImportError:
  504. continue
  505. if finder:
  506. loader = finder.find_module(fullname)
  507. if loader:
  508. return loader
  509. else:
  510. return None
  511. class _FileFinder:
  512. """File-based finder.
  513. Constructor takes a list of objects detailing what file extensions their
  514. loader supports along with whether it can be used for a package.
  515. """
  516. def __init__(self, path, *details):
  517. """Initialize with finder details."""
  518. packages = []
  519. modules = []
  520. for detail in details:
  521. modules.extend((suffix, detail.loader) for suffix in detail.suffixes)
  522. if detail.supports_packages:
  523. packages.extend((suffix, detail.loader)
  524. for suffix in detail.suffixes)
  525. self.packages = packages
  526. self.modules = modules
  527. self.path = path
  528. def find_module(self, fullname):
  529. """Try to find a loader for the specified module."""
  530. tail_module = fullname.rpartition('.')[2]
  531. base_path = _path_join(self.path, tail_module)
  532. if _path_isdir(base_path) and _case_ok(self.path, tail_module):
  533. for suffix, loader in self.packages:
  534. init_filename = '__init__' + suffix
  535. full_path = _path_join(base_path, init_filename)
  536. if (_path_isfile(full_path) and
  537. _case_ok(base_path, init_filename)):
  538. return loader(fullname, full_path)
  539. else:
  540. msg = "Not importing directory {}: missing __init__"
  541. _warnings.warn(msg.format(base_path), ImportWarning)
  542. for suffix, loader in self.modules:
  543. mod_filename = tail_module + suffix
  544. full_path = _path_join(self.path, mod_filename)
  545. if _path_isfile(full_path) and _case_ok(self.path, mod_filename):
  546. return loader(fullname, full_path)
  547. return None
  548. class _SourceFinderDetails:
  549. loader = _SourceFileLoader
  550. supports_packages = True
  551. def __init__(self):
  552. self.suffixes = _suffix_list(imp.PY_SOURCE)
  553. class _SourcelessFinderDetails:
  554. loader = _SourcelessFileLoader
  555. supports_packages = True
  556. def __init__(self):
  557. self.suffixes = _suffix_list(imp.PY_COMPILED)
  558. class _ExtensionFinderDetails:
  559. loader = _ExtensionFileLoader
  560. supports_packages = False
  561. def __init__(self):
  562. self.suffixes = _suffix_list(imp.C_EXTENSION)
  563. # Import itself ###############################################################
  564. def _file_path_hook(path):
  565. """If the path is a directory, return a file-based finder."""
  566. if _path_isdir(path):
  567. return _FileFinder(path, _ExtensionFinderDetails(),
  568. _SourceFinderDetails(),
  569. _SourcelessFinderDetails())
  570. else:
  571. raise ImportError("only directories are supported")
  572. _DEFAULT_PATH_HOOK = _file_path_hook
  573. class _DefaultPathFinder(PathFinder):
  574. """Subclass of PathFinder that implements implicit semantics for
  575. __import__."""
  576. @classmethod
  577. def _path_hooks(cls, path):
  578. """Search sys.path_hooks as well as implicit path hooks."""
  579. try:
  580. return super()._path_hooks(path)
  581. except ImportError:
  582. implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
  583. return super()._path_hooks(path, implicit_hooks)
  584. @classmethod
  585. def _path_importer_cache(cls, path):
  586. """Use the default path hook when None is stored in
  587. sys.path_importer_cache."""
  588. return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
  589. class _ImportLockContext:
  590. """Context manager for the import lock."""
  591. def __enter__(self):
  592. """Acquire the import lock."""
  593. imp.acquire_lock()
  594. def __exit__(self, exc_type, exc_value, exc_traceback):
  595. """Release the import lock regardless of any raised exceptions."""
  596. imp.release_lock()
  597. _IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
  598. _ERR_MSG = 'No module named {}'
  599. def _gcd_import(name, package=None, level=0):
  600. """Import and return the module based on its name, the package the call is
  601. being made from, and the level adjustment.
  602. This function represents the greatest common denominator of functionality
  603. between import_module and __import__. This includes settting __package__ if
  604. the loader did not.
  605. """
  606. if package:
  607. if not hasattr(package, 'rindex'):
  608. raise ValueError("__package__ not set to a string")
  609. elif package not in sys.modules:
  610. msg = ("Parent module {0!r} not loaded, cannot perform relative "
  611. "import")
  612. raise SystemError(msg.format(package))
  613. if not name and level == 0:
  614. raise ValueError("Empty module name")
  615. if level > 0:
  616. dot = len(package)
  617. for x in range(level, 1, -1):
  618. try:
  619. dot = package.rindex('.', 0, dot)
  620. except ValueError:
  621. raise ValueError("attempted relative import beyond "
  622. "top-level package")
  623. if name:
  624. name = "{0}.{1}".format(package[:dot], name)
  625. else:
  626. name = package[:dot]
  627. with _ImportLockContext():
  628. try:
  629. module = sys.modules[name]
  630. if module is None:
  631. message = ("import of {} halted; "
  632. "None in sys.modules".format(name))
  633. raise ImportError(message)
  634. return module
  635. except KeyError:
  636. pass
  637. parent = name.rpartition('.')[0]
  638. path = None
  639. if parent:
  640. if parent not in sys.modules:
  641. _gcd_import(parent)
  642. # Backwards-compatibility; be nicer to skip the dict lookup.
  643. parent_module = sys.modules[parent]
  644. try:
  645. path = parent_module.__path__
  646. except AttributeError:
  647. msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
  648. raise ImportError(msg)
  649. meta_path = sys.meta_path + _IMPLICIT_META_PATH
  650. for finder in meta_path:
  651. loader = finder.find_module(name, path)
  652. if loader is not None:
  653. # The parent import may have already imported this module.
  654. if name not in sys.modules:
  655. loader.load_module(name)
  656. break
  657. else:
  658. raise ImportError(_ERR_MSG.format(name))
  659. # Backwards-compatibility; be nicer to skip the dict lookup.
  660. module = sys.modules[name]
  661. if parent:
  662. # Set the module as an attribute on its parent.
  663. setattr(parent_module, name.rpartition('.')[2], module)
  664. # Set __package__ if the loader did not.
  665. if not hasattr(module, '__package__') or module.__package__ is None:
  666. # Watch out for what comes out of sys.modules to not be a module,
  667. # e.g. an int.
  668. try:
  669. module.__package__ = module.__name__
  670. if not hasattr(module, '__path__'):
  671. module.__package__ = module.__package__.rpartition('.')[0]
  672. except AttributeError:
  673. pass
  674. return module
  675. def __import__(name, globals={}, locals={}, fromlist=[], level=0):
  676. """Import a module.
  677. The 'globals' argument is used to infer where the import is occuring from
  678. to handle relative imports. The 'locals' argument is ignored. The
  679. 'fromlist' argument specifies what should exist as attributes on the module
  680. being imported (e.g. ``from module import <fromlist>``). The 'level'
  681. argument represents the package location to import from in a relative
  682. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  683. """
  684. if not hasattr(name, 'rpartition'):
  685. raise TypeError("module name must be str, not {}".format(type(name)))
  686. if level == 0:
  687. module = _gcd_import(name)
  688. else:
  689. # __package__ is not guaranteed to be defined or could be set to None
  690. # to represent that it's proper value is unknown
  691. package = globals.get('__package__')
  692. if package is None:
  693. package = globals['__name__']
  694. if '__path__' not in globals:
  695. package = package.rpartition('.')[0]
  696. module = _gcd_import(name, package, level)
  697. # The hell that is fromlist ...
  698. if not fromlist:
  699. # Return up to the first dot in 'name'. This is complicated by the fact
  700. # that 'name' may be relative.
  701. if level == 0:
  702. return sys.modules[name.partition('.')[0]]
  703. elif not name:
  704. return module
  705. else:
  706. cut_off = len(name) - len(name.partition('.')[0])
  707. return sys.modules[module.__name__[:-cut_off]]
  708. else:
  709. # If a package was imported, try to import stuff from fromlist.
  710. if hasattr(module, '__path__'):
  711. if '*' in fromlist and hasattr(module, '__all__'):
  712. fromlist = list(fromlist)
  713. fromlist.remove('*')
  714. fromlist.extend(module.__all__)
  715. for x in (y for y in fromlist if not hasattr(module,y)):
  716. try:
  717. _gcd_import('{0}.{1}'.format(module.__name__, x))
  718. except ImportError:
  719. pass
  720. return module