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.

1642 lines
57 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
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. #
  8. # IMPORTANT: Whenever making changes to this module, be sure to run
  9. # a top-level make in order to get the frozen version of the module
  10. # update. Not doing so, will result in the Makefile to fail for
  11. # all others who don't have a ./python around to freeze the module
  12. # in the early stages of compilation.
  13. #
  14. # See importlib._setup() for what is injected into the global namespace.
  15. # When editing this code be aware that code executed at import time CANNOT
  16. # reference any injected objects! This includes not only global code but also
  17. # anything specified at the class level.
  18. # XXX Make sure all public names have no single leading underscore and all
  19. # others do.
  20. # Bootstrap-related code ######################################################
  21. _CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin'
  22. def _make_relax_case():
  23. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  24. def _relax_case():
  25. """True if filenames must be checked case-insensitively."""
  26. return b'PYTHONCASEOK' in _os.environ
  27. else:
  28. def _relax_case():
  29. """True if filenames must be checked case-insensitively."""
  30. return False
  31. return _relax_case
  32. # TODO: Expose from marshal
  33. def _w_long(x):
  34. """Convert a 32-bit integer to little-endian.
  35. XXX Temporary until marshal's long functions are exposed.
  36. """
  37. x = int(x)
  38. int_bytes = []
  39. int_bytes.append(x & 0xFF)
  40. int_bytes.append((x >> 8) & 0xFF)
  41. int_bytes.append((x >> 16) & 0xFF)
  42. int_bytes.append((x >> 24) & 0xFF)
  43. return bytearray(int_bytes)
  44. # TODO: Expose from marshal
  45. def _r_long(int_bytes):
  46. """Convert 4 bytes in little-endian to an integer.
  47. XXX Temporary until marshal's long function are exposed.
  48. """
  49. x = int_bytes[0]
  50. x |= int_bytes[1] << 8
  51. x |= int_bytes[2] << 16
  52. x |= int_bytes[3] << 24
  53. return x
  54. def _path_join(*path_parts):
  55. """Replacement for os.path.join()."""
  56. new_parts = []
  57. for part in path_parts:
  58. if not part:
  59. continue
  60. new_parts.append(part)
  61. if part[-1] not in path_separators:
  62. new_parts.append(path_sep)
  63. return ''.join(new_parts[:-1]) # Drop superfluous path separator.
  64. def _path_split(path):
  65. """Replacement for os.path.split()."""
  66. for x in reversed(path):
  67. if x in path_separators:
  68. sep = x
  69. break
  70. else:
  71. sep = path_sep
  72. front, _, tail = path.rpartition(sep)
  73. return front, tail
  74. def _path_is_mode_type(path, mode):
  75. """Test whether the path is the specified mode type."""
  76. try:
  77. stat_info = _os.stat(path)
  78. except OSError:
  79. return False
  80. return (stat_info.st_mode & 0o170000) == mode
  81. # XXX Could also expose Modules/getpath.c:isfile()
  82. def _path_isfile(path):
  83. """Replacement for os.path.isfile."""
  84. return _path_is_mode_type(path, 0o100000)
  85. # XXX Could also expose Modules/getpath.c:isdir()
  86. def _path_isdir(path):
  87. """Replacement for os.path.isdir."""
  88. if not path:
  89. path = _os.getcwd()
  90. return _path_is_mode_type(path, 0o040000)
  91. def _write_atomic(path, data):
  92. """Best-effort function to write data to a path atomically.
  93. Be prepared to handle a FileExistsError if concurrent writing of the
  94. temporary file is attempted."""
  95. # id() is used to generate a pseudo-random filename.
  96. path_tmp = '{}.{}'.format(path, id(path))
  97. fd = _os.open(path_tmp, _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, 0o666)
  98. try:
  99. # We first write data to a temporary file, and then use os.replace() to
  100. # perform an atomic rename.
  101. with _io.FileIO(fd, 'wb') as file:
  102. file.write(data)
  103. _os.replace(path_tmp, path)
  104. except OSError:
  105. try:
  106. _os.unlink(path_tmp)
  107. except OSError:
  108. pass
  109. raise
  110. def _wrap(new, old):
  111. """Simple substitute for functools.update_wrapper."""
  112. for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
  113. if hasattr(old, replace):
  114. setattr(new, replace, getattr(old, replace))
  115. new.__dict__.update(old.__dict__)
  116. _code_type = type(_wrap.__code__)
  117. def new_module(name):
  118. """Create a new module.
  119. The module is not entered into sys.modules.
  120. """
  121. return type(_io)(name)
  122. # Module-level locking ########################################################
  123. # A dict mapping module names to weakrefs of _ModuleLock instances
  124. _module_locks = {}
  125. # A dict mapping thread ids to _ModuleLock instances
  126. _blocking_on = {}
  127. class _DeadlockError(RuntimeError):
  128. pass
  129. class _ModuleLock:
  130. """A recursive lock implementation which is able to detect deadlocks
  131. (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
  132. take locks B then A).
  133. """
  134. def __init__(self, name):
  135. self.lock = _thread.allocate_lock()
  136. self.wakeup = _thread.allocate_lock()
  137. self.name = name
  138. self.owner = None
  139. self.count = 0
  140. self.waiters = 0
  141. def has_deadlock(self):
  142. # Deadlock avoidance for concurrent circular imports.
  143. me = _thread.get_ident()
  144. tid = self.owner
  145. while True:
  146. lock = _blocking_on.get(tid)
  147. if lock is None:
  148. return False
  149. tid = lock.owner
  150. if tid == me:
  151. return True
  152. def acquire(self):
  153. """
  154. Acquire the module lock. If a potential deadlock is detected,
  155. a _DeadlockError is raised.
  156. Otherwise, the lock is always acquired and True is returned.
  157. """
  158. tid = _thread.get_ident()
  159. _blocking_on[tid] = self
  160. try:
  161. while True:
  162. with self.lock:
  163. if self.count == 0 or self.owner == tid:
  164. self.owner = tid
  165. self.count += 1
  166. return True
  167. if self.has_deadlock():
  168. raise _DeadlockError("deadlock detected by %r" % self)
  169. if self.wakeup.acquire(False):
  170. self.waiters += 1
  171. # Wait for a release() call
  172. self.wakeup.acquire()
  173. self.wakeup.release()
  174. finally:
  175. del _blocking_on[tid]
  176. def release(self):
  177. tid = _thread.get_ident()
  178. with self.lock:
  179. if self.owner != tid:
  180. raise RuntimeError("cannot release un-acquired lock")
  181. assert self.count > 0
  182. self.count -= 1
  183. if self.count == 0:
  184. self.owner = None
  185. if self.waiters:
  186. self.waiters -= 1
  187. self.wakeup.release()
  188. def __repr__(self):
  189. return "_ModuleLock(%r) at %d" % (self.name, id(self))
  190. class _DummyModuleLock:
  191. """A simple _ModuleLock equivalent for Python builds without
  192. multi-threading support."""
  193. def __init__(self, name):
  194. self.name = name
  195. self.count = 0
  196. def acquire(self):
  197. self.count += 1
  198. return True
  199. def release(self):
  200. if self.count == 0:
  201. raise RuntimeError("cannot release un-acquired lock")
  202. self.count -= 1
  203. def __repr__(self):
  204. return "_DummyModuleLock(%r) at %d" % (self.name, id(self))
  205. # The following two functions are for consumption by Python/import.c.
  206. def _get_module_lock(name):
  207. """Get or create the module lock for a given module name.
  208. Should only be called with the import lock taken."""
  209. lock = None
  210. if name in _module_locks:
  211. lock = _module_locks[name]()
  212. if lock is None:
  213. if _thread is None:
  214. lock = _DummyModuleLock(name)
  215. else:
  216. lock = _ModuleLock(name)
  217. def cb(_):
  218. del _module_locks[name]
  219. _module_locks[name] = _weakref.ref(lock, cb)
  220. return lock
  221. def _lock_unlock_module(name):
  222. """Release the global import lock, and acquires then release the
  223. module lock for a given module name.
  224. This is used to ensure a module is completely initialized, in the
  225. event it is being imported by another thread.
  226. Should only be called with the import lock taken."""
  227. lock = _get_module_lock(name)
  228. _imp.release_lock()
  229. try:
  230. lock.acquire()
  231. except _DeadlockError:
  232. # Concurrent circular import, we'll accept a partially initialized
  233. # module object.
  234. pass
  235. else:
  236. lock.release()
  237. # Finder/loader utility code ##################################################
  238. """Magic word to reject .pyc files generated by other Python versions.
  239. It should change for each incompatible change to the bytecode.
  240. The value of CR and LF is incorporated so if you ever read or write
  241. a .pyc file in text mode the magic number will be wrong; also, the
  242. Apple MPW compiler swaps their values, botching string constants.
  243. The magic numbers must be spaced apart at least 2 values, as the
  244. -U interpeter flag will cause MAGIC+1 being used. They have been
  245. odd numbers for some time now.
  246. There were a variety of old schemes for setting the magic number.
  247. The current working scheme is to increment the previous value by
  248. 10.
  249. Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
  250. number also includes a new "magic tag", i.e. a human readable string used
  251. to represent the magic number in __pycache__ directories. When you change
  252. the magic number, you must also set a new unique magic tag. Generally this
  253. can be named after the Python major version of the magic number bump, but
  254. it can really be anything, as long as it's different than anything else
  255. that's come before. The tags are included in the following table, starting
  256. with Python 3.2a0.
  257. Known values:
  258. Python 1.5: 20121
  259. Python 1.5.1: 20121
  260. Python 1.5.2: 20121
  261. Python 1.6: 50428
  262. Python 2.0: 50823
  263. Python 2.0.1: 50823
  264. Python 2.1: 60202
  265. Python 2.1.1: 60202
  266. Python 2.1.2: 60202
  267. Python 2.2: 60717
  268. Python 2.3a0: 62011
  269. Python 2.3a0: 62021
  270. Python 2.3a0: 62011 (!)
  271. Python 2.4a0: 62041
  272. Python 2.4a3: 62051
  273. Python 2.4b1: 62061
  274. Python 2.5a0: 62071
  275. Python 2.5a0: 62081 (ast-branch)
  276. Python 2.5a0: 62091 (with)
  277. Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
  278. Python 2.5b3: 62101 (fix wrong code: for x, in ...)
  279. Python 2.5b3: 62111 (fix wrong code: x += yield)
  280. Python 2.5c1: 62121 (fix wrong lnotab with for loops and
  281. storing constants that should have been removed)
  282. Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
  283. Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
  284. Python 2.6a1: 62161 (WITH_CLEANUP optimization)
  285. Python 3000: 3000
  286. 3010 (removed UNARY_CONVERT)
  287. 3020 (added BUILD_SET)
  288. 3030 (added keyword-only parameters)
  289. 3040 (added signature annotations)
  290. 3050 (print becomes a function)
  291. 3060 (PEP 3115 metaclass syntax)
  292. 3061 (string literals become unicode)
  293. 3071 (PEP 3109 raise changes)
  294. 3081 (PEP 3137 make __file__ and __name__ unicode)
  295. 3091 (kill str8 interning)
  296. 3101 (merge from 2.6a0, see 62151)
  297. 3103 (__file__ points to source file)
  298. Python 3.0a4: 3111 (WITH_CLEANUP optimization).
  299. Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
  300. Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
  301. change LIST_APPEND and SET_ADD, add MAP_ADD)
  302. Python 3.1a0: 3151 (optimize conditional branches:
  303. introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  304. Python 3.2a0: 3160 (add SETUP_WITH)
  305. tag: cpython-32
  306. Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
  307. tag: cpython-32
  308. Python 3.2a2 3180 (add DELETE_DEREF)
  309. Python 3.3a0 3190 __class__ super closure changed
  310. Python 3.3a0 3200 (__qualname__ added)
  311. 3210 (added size modulo 2**32 to the pyc header)
  312. Python 3.3a1 3220 (changed PEP 380 implementation)
  313. Python 3.3a4 3230 (revert changes to implicit __class__ closure)
  314. MAGIC must change whenever the bytecode emitted by the compiler may no
  315. longer be understood by older implementations of the eval loop (usually
  316. due to the addition of new opcodes).
  317. """
  318. _RAW_MAGIC_NUMBER = 3230 | ord('\r') << 16 | ord('\n') << 24
  319. _MAGIC_BYTES = bytes(_RAW_MAGIC_NUMBER >> n & 0xff for n in range(0, 25, 8))
  320. _PYCACHE = '__pycache__'
  321. SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
  322. DEBUG_BYTECODE_SUFFIXES = ['.pyc']
  323. OPTIMIZED_BYTECODE_SUFFIXES = ['.pyo']
  324. if __debug__:
  325. BYTECODE_SUFFIXES = DEBUG_BYTECODE_SUFFIXES
  326. else:
  327. BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES
  328. def cache_from_source(path, debug_override=None):
  329. """Given the path to a .py file, return the path to its .pyc/.pyo file.
  330. The .py file does not need to exist; this simply returns the path to the
  331. .pyc/.pyo file calculated as if the .py file were imported. The extension
  332. will be .pyc unless __debug__ is not defined, then it will be .pyo.
  333. If debug_override is not None, then it must be a boolean and is taken as
  334. the value of __debug__ instead.
  335. If sys.implementation.cache_tag is None then NotImplementedError is raised.
  336. """
  337. debug = __debug__ if debug_override is None else debug_override
  338. if debug:
  339. suffixes = DEBUG_BYTECODE_SUFFIXES
  340. else:
  341. suffixes = OPTIMIZED_BYTECODE_SUFFIXES
  342. head, tail = _path_split(path)
  343. base_filename, sep, _ = tail.partition('.')
  344. tag = sys.implementation.cache_tag
  345. if tag is None:
  346. raise NotImplementedError('sys.implementation.cache_tag is None')
  347. filename = ''.join([base_filename, sep, tag, suffixes[0]])
  348. return _path_join(head, _PYCACHE, filename)
  349. def source_from_cache(path):
  350. """Given the path to a .pyc./.pyo file, return the path to its .py file.
  351. The .pyc/.pyo file does not need to exist; this simply returns the path to
  352. the .py file calculated to correspond to the .pyc/.pyo file. If path does
  353. not conform to PEP 3147 format, ValueError will be raised. If
  354. sys.implementation.cache_tag is None then NotImplementedError is raised.
  355. """
  356. if sys.implementation.cache_tag is None:
  357. raise NotImplementedError('sys.implementation.cache_tag is None')
  358. head, pycache_filename = _path_split(path)
  359. head, pycache = _path_split(head)
  360. if pycache != _PYCACHE:
  361. raise ValueError('{} not bottom-level directory in '
  362. '{!r}'.format(_PYCACHE, path))
  363. if pycache_filename.count('.') != 2:
  364. raise ValueError('expected only 2 dots in '
  365. '{!r}'.format(pycache_filename))
  366. base_filename = pycache_filename.partition('.')[0]
  367. return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
  368. def _get_sourcefile(bytecode_path):
  369. """Convert a bytecode file path to a source path (if possible).
  370. This function exists purely for backwards-compatibility for
  371. PyImport_ExecCodeModuleWithFilenames() in the C API.
  372. """
  373. if len(bytecode_path) == 0:
  374. return None
  375. rest, _, extension = bytecode_path.rparition('.')
  376. if not rest or extension.lower()[-3:-1] != '.py':
  377. return bytecode_path
  378. try:
  379. source_path = source_from_cache(bytecode_path)
  380. except (NotImplementedError, ValueError):
  381. source_path = bytcode_path[-1:]
  382. return source_path if _path_isfile(source_stats) else bytecode_path
  383. def _verbose_message(message, *args):
  384. """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
  385. if sys.flags.verbose:
  386. if not message.startswith(('#', 'import ')):
  387. message = '# ' + message
  388. print(message.format(*args), file=sys.stderr)
  389. def set_package(fxn):
  390. """Set __package__ on the returned module."""
  391. def set_package_wrapper(*args, **kwargs):
  392. module = fxn(*args, **kwargs)
  393. if getattr(module, '__package__', None) is None:
  394. module.__package__ = module.__name__
  395. if not hasattr(module, '__path__'):
  396. module.__package__ = module.__package__.rpartition('.')[0]
  397. return module
  398. _wrap(set_package_wrapper, fxn)
  399. return set_package_wrapper
  400. def set_loader(fxn):
  401. """Set __loader__ on the returned module."""
  402. def set_loader_wrapper(self, *args, **kwargs):
  403. module = fxn(self, *args, **kwargs)
  404. if not hasattr(module, '__loader__'):
  405. module.__loader__ = self
  406. return module
  407. _wrap(set_loader_wrapper, fxn)
  408. return set_loader_wrapper
  409. def module_for_loader(fxn):
  410. """Decorator to handle selecting the proper module for loaders.
  411. The decorated function is passed the module to use instead of the module
  412. name. The module passed in to the function is either from sys.modules if
  413. it already exists or is a new module. If the module is new, then __name__
  414. is set the first argument to the method, __loader__ is set to self, and
  415. __package__ is set accordingly (if self.is_package() is defined) will be set
  416. before it is passed to the decorated function (if self.is_package() does
  417. not work for the module it will be set post-load).
  418. If an exception is raised and the decorator created the module it is
  419. subsequently removed from sys.modules.
  420. The decorator assumes that the decorated function takes the module name as
  421. the second argument.
  422. """
  423. def module_for_loader_wrapper(self, fullname, *args, **kwargs):
  424. module = sys.modules.get(fullname)
  425. is_reload = module is not None
  426. if not is_reload:
  427. # This must be done before open() is called as the 'io' module
  428. # implicitly imports 'locale' and would otherwise trigger an
  429. # infinite loop.
  430. module = new_module(fullname)
  431. sys.modules[fullname] = module
  432. module.__loader__ = self
  433. try:
  434. is_package = self.is_package(fullname)
  435. except (ImportError, AttributeError):
  436. pass
  437. else:
  438. if is_package:
  439. module.__package__ = fullname
  440. else:
  441. module.__package__ = fullname.rpartition('.')[0]
  442. try:
  443. module.__initializing__ = True
  444. # If __package__ was not set above, __import__() will do it later.
  445. return fxn(self, module, *args, **kwargs)
  446. except:
  447. if not is_reload:
  448. del sys.modules[fullname]
  449. raise
  450. finally:
  451. module.__initializing__ = False
  452. _wrap(module_for_loader_wrapper, fxn)
  453. return module_for_loader_wrapper
  454. def _check_name(method):
  455. """Decorator to verify that the module being requested matches the one the
  456. loader can handle.
  457. The first argument (self) must define _name which the second argument is
  458. compared against. If the comparison fails then ImportError is raised.
  459. """
  460. def _check_name_wrapper(self, name=None, *args, **kwargs):
  461. if name is None:
  462. name = self.name
  463. elif self.name != name:
  464. raise ImportError("loader cannot handle %s" % name, name=name)
  465. return method(self, name, *args, **kwargs)
  466. _wrap(_check_name_wrapper, method)
  467. return _check_name_wrapper
  468. def _requires_builtin(fxn):
  469. """Decorator to verify the named module is built-in."""
  470. def _requires_builtin_wrapper(self, fullname):
  471. if fullname not in sys.builtin_module_names:
  472. raise ImportError("{} is not a built-in module".format(fullname),
  473. name=fullname)
  474. return fxn(self, fullname)
  475. _wrap(_requires_builtin_wrapper, fxn)
  476. return _requires_builtin_wrapper
  477. def _requires_frozen(fxn):
  478. """Decorator to verify the named module is frozen."""
  479. def _requires_frozen_wrapper(self, fullname):
  480. if not _imp.is_frozen(fullname):
  481. raise ImportError("{} is not a frozen module".format(fullname),
  482. name=fullname)
  483. return fxn(self, fullname)
  484. _wrap(_requires_frozen_wrapper, fxn)
  485. return _requires_frozen_wrapper
  486. # Loaders #####################################################################
  487. class BuiltinImporter:
  488. """Meta path import for built-in modules.
  489. All methods are either class or static methods to avoid the need to
  490. instantiate the class.
  491. """
  492. @classmethod
  493. def module_repr(cls, module):
  494. return "<module '{}' (built-in)>".format(module.__name__)
  495. @classmethod
  496. def find_module(cls, fullname, path=None):
  497. """Find the built-in module.
  498. If 'path' is ever specified then the search is considered a failure.
  499. """
  500. if path is not None:
  501. return None
  502. return cls if _imp.is_builtin(fullname) else None
  503. @classmethod
  504. @set_package
  505. @set_loader
  506. @_requires_builtin
  507. def load_module(cls, fullname):
  508. """Load a built-in module."""
  509. is_reload = fullname in sys.modules
  510. try:
  511. return cls._exec_module(fullname)
  512. except:
  513. if not is_reload and fullname in sys.modules:
  514. del sys.modules[fullname]
  515. raise
  516. @classmethod
  517. def _exec_module(cls, fullname):
  518. """Helper for load_module, allowing to isolate easily (when
  519. looking at a traceback) whether an error comes from executing
  520. an imported module's code."""
  521. return _imp.init_builtin(fullname)
  522. @classmethod
  523. @_requires_builtin
  524. def get_code(cls, fullname):
  525. """Return None as built-in modules do not have code objects."""
  526. return None
  527. @classmethod
  528. @_requires_builtin
  529. def get_source(cls, fullname):
  530. """Return None as built-in modules do not have source code."""
  531. return None
  532. @classmethod
  533. @_requires_builtin
  534. def is_package(cls, fullname):
  535. """Return False as built-in modules are never packages."""
  536. return False
  537. class FrozenImporter:
  538. """Meta path import for frozen modules.
  539. All methods are either class or static methods to avoid the need to
  540. instantiate the class.
  541. """
  542. @classmethod
  543. def module_repr(cls, m):
  544. return "<module '{}' (frozen)>".format(m.__name__)
  545. @classmethod
  546. def find_module(cls, fullname, path=None):
  547. """Find a frozen module."""
  548. return cls if _imp.is_frozen(fullname) else None
  549. @classmethod
  550. @set_package
  551. @set_loader
  552. @_requires_frozen
  553. def load_module(cls, fullname):
  554. """Load a frozen module."""
  555. is_reload = fullname in sys.modules
  556. try:
  557. m = cls._exec_module(fullname)
  558. # Let our own module_repr() method produce a suitable repr.
  559. del m.__file__
  560. return m
  561. except:
  562. if not is_reload and fullname in sys.modules:
  563. del sys.modules[fullname]
  564. raise
  565. @classmethod
  566. @_requires_frozen
  567. def get_code(cls, fullname):
  568. """Return the code object for the frozen module."""
  569. return _imp.get_frozen_object(fullname)
  570. @classmethod
  571. @_requires_frozen
  572. def get_source(cls, fullname):
  573. """Return None as frozen modules do not have source code."""
  574. return None
  575. @classmethod
  576. @_requires_frozen
  577. def is_package(cls, fullname):
  578. """Return if the frozen module is a package."""
  579. return _imp.is_frozen_package(fullname)
  580. @classmethod
  581. def _exec_module(cls, fullname):
  582. """Helper for load_module, allowing to isolate easily (when
  583. looking at a traceback) whether an error comes from executing
  584. an imported module's code."""
  585. return _imp.init_frozen(fullname)
  586. class _LoaderBasics:
  587. """Base class of common code needed by both SourceLoader and
  588. SourcelessFileLoader."""
  589. def is_package(self, fullname):
  590. """Concrete implementation of InspectLoader.is_package by checking if
  591. the path returned by get_filename has a filename of '__init__.py'."""
  592. filename = _path_split(self.get_filename(fullname))[1]
  593. filename_base = filename.rsplit('.', 1)[0]
  594. tail_name = fullname.rpartition('.')[2]
  595. return filename_base == '__init__' and tail_name != '__init__'
  596. def _bytes_from_bytecode(self, fullname, data, bytecode_path, source_stats):
  597. """Return the marshalled bytes from bytecode, verifying the magic
  598. number, timestamp and source size along the way.
  599. If source_stats is None then skip the timestamp check.
  600. """
  601. magic = data[:4]
  602. raw_timestamp = data[4:8]
  603. raw_size = data[8:12]
  604. if magic != _MAGIC_BYTES:
  605. msg = 'bad magic number in {!r}: {!r}'.format(fullname, magic)
  606. raise ImportError(msg, name=fullname, path=bytecode_path)
  607. elif len(raw_timestamp) != 4:
  608. message = 'bad timestamp in {}'.format(fullname)
  609. _verbose_message(message)
  610. raise EOFError(message)
  611. elif len(raw_size) != 4:
  612. message = 'bad size in {}'.format(fullname)
  613. _verbose_message(message)
  614. raise EOFError(message)
  615. if source_stats is not None:
  616. try:
  617. source_mtime = int(source_stats['mtime'])
  618. except KeyError:
  619. pass
  620. else:
  621. if _r_long(raw_timestamp) != source_mtime:
  622. message = 'bytecode is stale for {}'.format(fullname)
  623. _verbose_message(message)
  624. raise ImportError(message, name=fullname,
  625. path=bytecode_path)
  626. try:
  627. source_size = source_stats['size'] & 0xFFFFFFFF
  628. except KeyError:
  629. pass
  630. else:
  631. if _r_long(raw_size) != source_size:
  632. raise ImportError(
  633. "bytecode is stale for {}".format(fullname),
  634. name=fullname, path=bytecode_path)
  635. # Can't return the code object as errors from marshal loading need to
  636. # propagate even when source is available.
  637. return data[12:]
  638. @module_for_loader
  639. def _load_module(self, module, *, sourceless=False):
  640. """Helper for load_module able to handle either source or sourceless
  641. loading."""
  642. name = module.__name__
  643. code_object = self.get_code(name)
  644. module.__file__ = self.get_filename(name)
  645. if not sourceless:
  646. try:
  647. module.__cached__ = cache_from_source(module.__file__)
  648. except NotImplementedError:
  649. module.__cached__ = module.__file__
  650. else:
  651. module.__cached__ = module.__file__
  652. module.__package__ = name
  653. if self.is_package(name):
  654. module.__path__ = [_path_split(module.__file__)[0]]
  655. else:
  656. module.__package__ = module.__package__.rpartition('.')[0]
  657. module.__loader__ = self
  658. self._exec_module(code_object, module.__dict__)
  659. return module
  660. def _exec_module(self, code_object, module_dict):
  661. """Helper for _load_module, allowing to isolate easily (when
  662. looking at a traceback) whether an error comes from executing
  663. an imported module's code."""
  664. exec(code_object, module_dict)
  665. class SourceLoader(_LoaderBasics):
  666. def path_mtime(self, path):
  667. """Optional method that returns the modification time (an int) for the
  668. specified path, where path is a str.
  669. """
  670. raise NotImplementedError
  671. def path_stats(self, path):
  672. """Optional method returning a metadata dict for the specified path
  673. to by the path (str).
  674. Possible keys:
  675. - 'mtime' (mandatory) is the numeric timestamp of last source
  676. code modification;
  677. - 'size' (optional) is the size in bytes of the source code.
  678. Implementing this method allows the loader to read bytecode files.
  679. """
  680. return {'mtime': self.path_mtime(path)}
  681. def set_data(self, path, data):
  682. """Optional method which writes data (bytes) to a file path (a str).
  683. Implementing this method allows for the writing of bytecode files.
  684. """
  685. raise NotImplementedError
  686. def get_source(self, fullname):
  687. """Concrete implementation of InspectLoader.get_source."""
  688. import tokenize
  689. path = self.get_filename(fullname)
  690. try:
  691. source_bytes = self.get_data(path)
  692. except IOError as exc:
  693. raise ImportError("source not available through get_data()",
  694. name=fullname) from exc
  695. readsource = _io.BytesIO(source_bytes).readline
  696. try:
  697. encoding = tokenize.detect_encoding(readsource)
  698. except SyntaxError as exc:
  699. raise ImportError("Failed to detect encoding",
  700. name=fullname) from exc
  701. newline_decoder = _io.IncrementalNewlineDecoder(None, True)
  702. try:
  703. return newline_decoder.decode(source_bytes.decode(encoding[0]))
  704. except UnicodeDecodeError as exc:
  705. raise ImportError("Failed to decode source file",
  706. name=fullname) from exc
  707. def get_code(self, fullname):
  708. """Concrete implementation of InspectLoader.get_code.
  709. Reading of bytecode requires path_stats to be implemented. To write
  710. bytecode, set_data must also be implemented.
  711. """
  712. source_path = self.get_filename(fullname)
  713. source_mtime = None
  714. try:
  715. bytecode_path = cache_from_source(source_path)
  716. except NotImplementedError:
  717. bytecode_path = None
  718. else:
  719. try:
  720. st = self.path_stats(source_path)
  721. except NotImplementedError:
  722. pass
  723. else:
  724. source_mtime = int(st['mtime'])
  725. try:
  726. data = self.get_data(bytecode_path)
  727. except IOError:
  728. pass
  729. else:
  730. try:
  731. bytes_data = self._bytes_from_bytecode(fullname, data,
  732. bytecode_path,
  733. st)
  734. except (ImportError, EOFError):
  735. pass
  736. else:
  737. _verbose_message('{} matches {}', bytecode_path,
  738. source_path)
  739. found = marshal.loads(bytes_data)
  740. if isinstance(found, _code_type):
  741. _imp._fix_co_filename(found, source_path)
  742. _verbose_message('code object from {}',
  743. bytecode_path)
  744. return found
  745. else:
  746. msg = "Non-code object in {}"
  747. raise ImportError(msg.format(bytecode_path),
  748. name=fullname, path=bytecode_path)
  749. source_bytes = self.get_data(source_path)
  750. code_object = compile(source_bytes, source_path, 'exec',
  751. dont_inherit=True)
  752. _verbose_message('code object from {}', source_path)
  753. if (not sys.dont_write_bytecode and bytecode_path is not None and
  754. source_mtime is not None):
  755. data = bytearray(_MAGIC_BYTES)
  756. data.extend(_w_long(source_mtime))
  757. data.extend(_w_long(len(source_bytes)))
  758. data.extend(marshal.dumps(code_object))
  759. try:
  760. self.set_data(bytecode_path, data)
  761. _verbose_message('wrote {!r}', bytecode_path)
  762. except NotImplementedError:
  763. pass
  764. return code_object
  765. def load_module(self, fullname):
  766. """Concrete implementation of Loader.load_module.
  767. Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
  768. implemented to load source code. Use of bytecode is dictated by whether
  769. get_code uses/writes bytecode.
  770. """
  771. return self._load_module(fullname)
  772. class FileLoader:
  773. """Base file loader class which implements the loader protocol methods that
  774. require file system usage."""
  775. def __init__(self, fullname, path):
  776. """Cache the module name and the path to the file found by the
  777. finder."""
  778. self.name = fullname
  779. self.path = path
  780. @_check_name
  781. def load_module(self, fullname):
  782. """Load a module from a file."""
  783. # Issue #14857: Avoid the zero-argument form so the implementation
  784. # of that form can be updated without breaking the frozen module
  785. return super(FileLoader, self).load_module(fullname)
  786. @_check_name
  787. def get_filename(self, fullname):
  788. """Return the path to the source file as found by the finder."""
  789. return self.path
  790. def get_data(self, path):
  791. """Return the data from path as raw bytes."""
  792. with _io.FileIO(path, 'r') as file:
  793. return file.read()
  794. class SourceFileLoader(FileLoader, SourceLoader):
  795. """Concrete implementation of SourceLoader using the file system."""
  796. def path_stats(self, path):
  797. """Return the metadat for the path."""
  798. st = _os.stat(path)
  799. return {'mtime': st.st_mtime, 'size': st.st_size}
  800. def set_data(self, path, data):
  801. """Write bytes data to a file."""
  802. parent, filename = _path_split(path)
  803. path_parts = []
  804. # Figure out what directories are missing.
  805. while parent and not _path_isdir(parent):
  806. parent, part = _path_split(parent)
  807. path_parts.append(part)
  808. # Create needed directories.
  809. for part in reversed(path_parts):
  810. parent = _path_join(parent, part)
  811. try:
  812. _os.mkdir(parent)
  813. except FileExistsError:
  814. # Probably another Python process already created the dir.
  815. continue
  816. except PermissionError:
  817. # If can't get proper access, then just forget about writing
  818. # the data.
  819. return
  820. try:
  821. _write_atomic(path, data)
  822. _verbose_message('created {!r}', path)
  823. except (PermissionError, FileExistsError):
  824. # Don't worry if you can't write bytecode or someone is writing
  825. # it at the same time.
  826. pass
  827. class SourcelessFileLoader(FileLoader, _LoaderBasics):
  828. """Loader which handles sourceless file imports."""
  829. def load_module(self, fullname):
  830. return self._load_module(fullname, sourceless=True)
  831. def get_code(self, fullname):
  832. path = self.get_filename(fullname)
  833. data = self.get_data(path)
  834. bytes_data = self._bytes_from_bytecode(fullname, data, path, None)
  835. found = marshal.loads(bytes_data)
  836. if isinstance(found, _code_type):
  837. _verbose_message('code object from {!r}', path)
  838. return found
  839. else:
  840. raise ImportError("Non-code object in {}".format(path),
  841. name=fullname, path=path)
  842. def get_source(self, fullname):
  843. """Return None as there is no source code."""
  844. return None
  845. class ExtensionFileLoader:
  846. """Loader for extension modules.
  847. The constructor is designed to work with FileFinder.
  848. """
  849. def __init__(self, name, path):
  850. self.name = name
  851. self.path = path
  852. @_check_name
  853. @set_package
  854. @set_loader
  855. def load_module(self, fullname):
  856. """Load an extension module."""
  857. is_reload = fullname in sys.modules
  858. try:
  859. module = self._exec_module(fullname, self.path)
  860. _verbose_message('extension module loaded from {!r}', self.path)
  861. return module
  862. except:
  863. if not is_reload and fullname in sys.modules:
  864. del sys.modules[fullname]
  865. raise
  866. def is_package(self, fullname):
  867. """Return False as an extension module can never be a package."""
  868. return False
  869. def get_code(self, fullname):
  870. """Return None as an extension module cannot create a code object."""
  871. return None
  872. def get_source(self, fullname):
  873. """Return None as extension modules have no source code."""
  874. return None
  875. def _exec_module(self, fullname, path):
  876. """Helper for load_module, allowing to isolate easily (when
  877. looking at a traceback) whether an error comes from executing
  878. an imported module's code."""
  879. return _imp.load_dynamic(fullname, path)
  880. class _NamespacePath:
  881. """Represents a namespace package's path. It uses the module name
  882. to find its parent module, and from there it looks up the parent's
  883. __path__. When this changes, the module's own path is recomputed,
  884. using path_finder. For top-leve modules, the parent module's path
  885. is sys.path."""
  886. def __init__(self, name, path, path_finder):
  887. self._name = name
  888. self._path = path
  889. self._last_parent_path = tuple(self._get_parent_path())
  890. self._path_finder = path_finder
  891. def _find_parent_path_names(self):
  892. """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
  893. parent, dot, me = self._name.rpartition('.')
  894. if dot == '':
  895. # This is a top-level module. sys.path contains the parent path.
  896. return 'sys', 'path'
  897. # Not a top-level module. parent-module.__path__ contains the
  898. # parent path.
  899. return parent, '__path__'
  900. def _get_parent_path(self):
  901. parent_module_name, path_attr_name = self._find_parent_path_names()
  902. return getattr(sys.modules[parent_module_name], path_attr_name)
  903. def _recalculate(self):
  904. # If the parent's path has changed, recalculate _path
  905. parent_path = tuple(self._get_parent_path()) # Make a copy
  906. if parent_path != self._last_parent_path:
  907. loader, new_path = self._path_finder(self._name, parent_path)
  908. # Note that no changes are made if a loader is returned, but we
  909. # do remember the new parent path
  910. if loader is None:
  911. self._path = new_path
  912. self._last_parent_path = parent_path # Save the copy
  913. return self._path
  914. def __iter__(self):
  915. return iter(self._recalculate())
  916. def __len__(self):
  917. return len(self._recalculate())
  918. def __repr__(self):
  919. return "_NamespacePath({!r})".format(self._path)
  920. def __contains__(self, item):
  921. return item in self._recalculate()
  922. def append(self, item):
  923. self._path.append(item)
  924. class NamespaceLoader:
  925. def __init__(self, name, path, path_finder):
  926. self._path = _NamespacePath(name, path, path_finder)
  927. @classmethod
  928. def module_repr(cls, module):
  929. return "<module '{}' (namespace)>".format(module.__name__)
  930. @module_for_loader
  931. def load_module(self, module):
  932. """Load a namespace module."""
  933. _verbose_message('namespace module loaded with path {!r}', self._path)
  934. module.__path__ = self._path
  935. return module
  936. # Finders #####################################################################
  937. class PathFinder:
  938. """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
  939. @classmethod
  940. def _path_hooks(cls, path):
  941. """Search sequence of hooks for a finder for 'path'.
  942. If 'hooks' is false then use sys.path_hooks.
  943. """
  944. if not sys.path_hooks:
  945. _warnings.warn('sys.path_hooks is empty', ImportWarning)
  946. for hook in sys.path_hooks:
  947. try:
  948. return hook(path)
  949. except ImportError:
  950. continue
  951. else:
  952. return None
  953. @classmethod
  954. def _path_importer_cache(cls, path):
  955. """Get the finder for the path from sys.path_importer_cache.
  956. If the path is not in the cache, find the appropriate finder and cache
  957. it. If no finder is available, store None.
  958. """
  959. if path == '':
  960. path = '.'
  961. try:
  962. finder = sys.path_importer_cache[path]
  963. except KeyError:
  964. finder = cls._path_hooks(path)
  965. sys.path_importer_cache[path] = finder
  966. return finder
  967. @classmethod
  968. def _get_loader(cls, fullname, path):
  969. """Find the loader or namespace_path for this module/package name."""
  970. # If this ends up being a namespace package, namespace_path is
  971. # the list of paths that will become its __path__
  972. namespace_path = []
  973. for entry in path:
  974. finder = cls._path_importer_cache(entry)
  975. if finder is not None:
  976. if hasattr(finder, 'find_loader'):
  977. loader, portions = finder.find_loader(fullname)
  978. else:
  979. loader = finder.find_module(fullname)
  980. portions = []
  981. if loader is not None:
  982. # We found a loader: return it immediately.
  983. return (loader, namespace_path)
  984. # This is possibly part of a namespace package.
  985. # Remember these path entries (if any) for when we
  986. # create a namespace package, and continue iterating
  987. # on path.
  988. namespace_path.extend(portions)
  989. else:
  990. return (None, namespace_path)
  991. @classmethod
  992. def find_module(cls, fullname, path=None):
  993. """Find the module on sys.path or 'path' based on sys.path_hooks and
  994. sys.path_importer_cache."""
  995. if path is None:
  996. path = sys.path
  997. loader, namespace_path = cls._get_loader(fullname, path)
  998. if loader is not None:
  999. return loader
  1000. else:
  1001. if namespace_path:
  1002. # We found at least one namespace path. Return a
  1003. # loader which can create the namespace package.
  1004. return NamespaceLoader(fullname, namespace_path, cls._get_loader)
  1005. else:
  1006. return None
  1007. class FileFinder:
  1008. """File-based finder.
  1009. Interactions with the file system are cached for performance, being
  1010. refreshed when the directory the finder is handling has been modified.
  1011. """
  1012. def __init__(self, path, *details):
  1013. """Initialize with the path to search on and a variable number of
  1014. 3-tuples containing the loader, file suffixes the loader recognizes,
  1015. and a boolean of whether the loader handles packages."""
  1016. packages = []
  1017. modules = []
  1018. for loader, suffixes, supports_packages in details:
  1019. modules.extend((suffix, loader) for suffix in suffixes)
  1020. if supports_packages:
  1021. packages.extend((suffix, loader) for suffix in suffixes)
  1022. self.packages = packages
  1023. self.modules = modules
  1024. # Base (directory) path
  1025. self.path = path or '.'
  1026. self._path_mtime = -1
  1027. self._path_cache = set()
  1028. self._relaxed_path_cache = set()
  1029. def invalidate_caches(self):
  1030. """Invalidate the directory mtime."""
  1031. self._path_mtime = -1
  1032. def find_module(self, fullname):
  1033. """Try to find a loader for the specified module."""
  1034. # Call find_loader(). If it returns a string (indicating this
  1035. # is a namespace package portion), generate a warning and
  1036. # return None.
  1037. loader, portions = self.find_loader(fullname)
  1038. assert len(portions) in [0, 1]
  1039. if loader is None and len(portions):
  1040. msg = "Not importing directory {}: missing __init__"
  1041. _warnings.warn(msg.format(portions[0]), ImportWarning)
  1042. return loader
  1043. def find_loader(self, fullname):
  1044. """Try to find a loader for the specified module, or the namespace
  1045. package portions. Returns (loader, list-of-portions)."""
  1046. is_namespace = False
  1047. tail_module = fullname.rpartition('.')[2]
  1048. try:
  1049. mtime = _os.stat(self.path).st_mtime
  1050. except OSError:
  1051. mtime = -1
  1052. if mtime != self._path_mtime:
  1053. self._fill_cache()
  1054. self._path_mtime = mtime
  1055. # tail_module keeps the original casing, for __file__ and friends
  1056. if _relax_case():
  1057. cache = self._relaxed_path_cache
  1058. cache_module = tail_module.lower()
  1059. else:
  1060. cache = self._path_cache
  1061. cache_module = tail_module
  1062. # Check if the module is the name of a directory (and thus a package).
  1063. if cache_module in cache:
  1064. base_path = _path_join(self.path, tail_module)
  1065. if _path_isdir(base_path):
  1066. for suffix, loader in self.packages:
  1067. init_filename = '__init__' + suffix
  1068. full_path = _path_join(base_path, init_filename)
  1069. if _path_isfile(full_path):
  1070. return (loader(fullname, full_path), [base_path])
  1071. else:
  1072. # A namespace package, return the path if we don't also
  1073. # find a module in the next section.
  1074. is_namespace = True
  1075. # Check for a file w/ a proper suffix exists.
  1076. for suffix, loader in self.modules:
  1077. if cache_module + suffix in cache:
  1078. full_path = _path_join(self.path, tail_module + suffix)
  1079. if _path_isfile(full_path):
  1080. return (loader(fullname, full_path), [])
  1081. if is_namespace:
  1082. return (None, [base_path])
  1083. return (None, [])
  1084. def _fill_cache(self):
  1085. """Fill the cache of potential modules and packages for this directory."""
  1086. path = self.path
  1087. contents = _os.listdir(path)
  1088. # We store two cached versions, to handle runtime changes of the
  1089. # PYTHONCASEOK environment variable.
  1090. if not sys.platform.startswith('win'):
  1091. self._path_cache = set(contents)
  1092. else:
  1093. # Windows users can import modules with case-insensitive file
  1094. # suffixes (for legacy reasons). Make the suffix lowercase here
  1095. # so it's done once instead of for every import. This is safe as
  1096. # the specified suffixes to check against are always specified in a
  1097. # case-sensitive manner.
  1098. lower_suffix_contents = set()
  1099. for item in contents:
  1100. name, dot, suffix = item.partition('.')
  1101. if dot:
  1102. new_name = '{}.{}'.format(name, suffix.lower())
  1103. else:
  1104. new_name = name
  1105. lower_suffix_contents.add(new_name)
  1106. self._path_cache = lower_suffix_contents
  1107. if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
  1108. self._relaxed_path_cache = set(fn.lower() for fn in contents)
  1109. @classmethod
  1110. def path_hook(cls, *loader_details):
  1111. """A class method which returns a closure to use on sys.path_hook
  1112. which will return an instance using the specified loaders and the path
  1113. called on the closure.
  1114. If the path called on the closure is not a directory, ImportError is
  1115. raised.
  1116. """
  1117. def path_hook_for_FileFinder(path):
  1118. """Path hook for importlib.machinery.FileFinder."""
  1119. if not _path_isdir(path):
  1120. raise ImportError("only directories are supported", path=path)
  1121. return cls(path, *loader_details)
  1122. return path_hook_for_FileFinder
  1123. def __repr__(self):
  1124. return "FileFinder(%r)" % (self.path,)
  1125. # Import itself ###############################################################
  1126. class _ImportLockContext:
  1127. """Context manager for the import lock."""
  1128. def __enter__(self):
  1129. """Acquire the import lock."""
  1130. _imp.acquire_lock()
  1131. def __exit__(self, exc_type, exc_value, exc_traceback):
  1132. """Release the import lock regardless of any raised exceptions."""
  1133. _imp.release_lock()
  1134. def _resolve_name(name, package, level):
  1135. """Resolve a relative module name to an absolute one."""
  1136. bits = package.rsplit('.', level - 1)
  1137. if len(bits) < level:
  1138. raise ValueError('attempted relative import beyond top-level package')
  1139. base = bits[0]
  1140. return '{}.{}'.format(base, name) if name else base
  1141. def _find_module(name, path):
  1142. """Find a module's loader."""
  1143. if not sys.meta_path:
  1144. _warnings.warn('sys.meta_path is empty', ImportWarning)
  1145. for finder in sys.meta_path:
  1146. with _ImportLockContext():
  1147. loader = finder.find_module(name, path)
  1148. if loader is not None:
  1149. # The parent import may have already imported this module.
  1150. if name not in sys.modules:
  1151. return loader
  1152. else:
  1153. return sys.modules[name].__loader__
  1154. else:
  1155. return None
  1156. def _sanity_check(name, package, level):
  1157. """Verify arguments are "sane"."""
  1158. if not isinstance(name, str):
  1159. raise TypeError("module name must be str, not {}".format(type(name)))
  1160. if level < 0:
  1161. raise ValueError('level must be >= 0')
  1162. if package:
  1163. if not isinstance(package, str):
  1164. raise TypeError("__package__ not set to a string")
  1165. elif package not in sys.modules:
  1166. msg = ("Parent module {!r} not loaded, cannot perform relative "
  1167. "import")
  1168. raise SystemError(msg.format(package))
  1169. if not name and level == 0:
  1170. raise ValueError("Empty module name")
  1171. _ERR_MSG = 'No module named {!r}'
  1172. def _find_and_load_unlocked(name, import_):
  1173. path = None
  1174. parent = name.rpartition('.')[0]
  1175. if parent:
  1176. if parent not in sys.modules:
  1177. import_(parent)
  1178. # Crazy side-effects!
  1179. if name in sys.modules:
  1180. return sys.modules[name]
  1181. # Backwards-compatibility; be nicer to skip the dict lookup.
  1182. parent_module = sys.modules[parent]
  1183. try:
  1184. path = parent_module.__path__
  1185. except AttributeError:
  1186. msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
  1187. raise ImportError(msg, name=name)
  1188. loader = _find_module(name, path)
  1189. if loader is None:
  1190. raise ImportError(_ERR_MSG.format(name), name=name)
  1191. elif name not in sys.modules:
  1192. # The parent import may have already imported this module.
  1193. loader.load_module(name)
  1194. _verbose_message('import {!r} # {!r}', name, loader)
  1195. # Backwards-compatibility; be nicer to skip the dict lookup.
  1196. module = sys.modules[name]
  1197. if parent:
  1198. # Set the module as an attribute on its parent.
  1199. parent_module = sys.modules[parent]
  1200. setattr(parent_module, name.rpartition('.')[2], module)
  1201. # Set __package__ if the loader did not.
  1202. if getattr(module, '__package__', None) is None:
  1203. try:
  1204. module.__package__ = module.__name__
  1205. if not hasattr(module, '__path__'):
  1206. module.__package__ = module.__package__.rpartition('.')[0]
  1207. except AttributeError:
  1208. pass
  1209. # Set loader if need be.
  1210. if not hasattr(module, '__loader__'):
  1211. try:
  1212. module.__loader__ = loader
  1213. except AttributeError:
  1214. pass
  1215. return module
  1216. def _find_and_load(name, import_):
  1217. """Find and load the module, and release the import lock."""
  1218. try:
  1219. lock = _get_module_lock(name)
  1220. finally:
  1221. _imp.release_lock()
  1222. lock.acquire()
  1223. try:
  1224. return _find_and_load_unlocked(name, import_)
  1225. finally:
  1226. lock.release()
  1227. def _gcd_import(name, package=None, level=0):
  1228. """Import and return the module based on its name, the package the call is
  1229. being made from, and the level adjustment.
  1230. This function represents the greatest common denominator of functionality
  1231. between import_module and __import__. This includes setting __package__ if
  1232. the loader did not.
  1233. """
  1234. _sanity_check(name, package, level)
  1235. if level > 0:
  1236. name = _resolve_name(name, package, level)
  1237. _imp.acquire_lock()
  1238. if name not in sys.modules:
  1239. return _find_and_load(name, _gcd_import)
  1240. module = sys.modules[name]
  1241. if module is None:
  1242. _imp.release_lock()
  1243. message = ("import of {} halted; "
  1244. "None in sys.modules".format(name))
  1245. raise ImportError(message, name=name)
  1246. _lock_unlock_module(name)
  1247. return module
  1248. def _handle_fromlist(module, fromlist, import_):
  1249. """Figure out what __import__ should return.
  1250. The import_ parameter is a callable which takes the name of module to
  1251. import. It is required to decouple the function from assuming importlib's
  1252. import implementation is desired.
  1253. """
  1254. # The hell that is fromlist ...
  1255. # If a package was imported, try to import stuff from fromlist.
  1256. if hasattr(module, '__path__'):
  1257. if '*' in fromlist:
  1258. fromlist = list(fromlist)
  1259. fromlist.remove('*')
  1260. if hasattr(module, '__all__'):
  1261. fromlist.extend(module.__all__)
  1262. for x in fromlist:
  1263. if not hasattr(module, x):
  1264. import_('{}.{}'.format(module.__name__, x))
  1265. return module
  1266. def _calc___package__(globals):
  1267. """Calculate what __package__ should be.
  1268. __package__ is not guaranteed to be defined or could be set to None
  1269. to represent that its proper value is unknown.
  1270. """
  1271. package = globals.get('__package__')
  1272. if package is None:
  1273. package = globals['__name__']
  1274. if '__path__' not in globals:
  1275. package = package.rpartition('.')[0]
  1276. return package
  1277. def __import__(name, globals={}, locals={}, fromlist=[], level=0):
  1278. """Import a module.
  1279. The 'globals' argument is used to infer where the import is occuring from
  1280. to handle relative imports. The 'locals' argument is ignored. The
  1281. 'fromlist' argument specifies what should exist as attributes on the module
  1282. being imported (e.g. ``from module import <fromlist>``). The 'level'
  1283. argument represents the package location to import from in a relative
  1284. import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
  1285. """
  1286. if level == 0:
  1287. module = _gcd_import(name)
  1288. else:
  1289. package = _calc___package__(globals)
  1290. module = _gcd_import(name, package, level)
  1291. if not fromlist:
  1292. # Return up to the first dot in 'name'. This is complicated by the fact
  1293. # that 'name' may be relative.
  1294. if level == 0:
  1295. return _gcd_import(name.partition('.')[0])
  1296. elif not name:
  1297. return module
  1298. else:
  1299. cut_off = len(name) - len(name.partition('.')[0])
  1300. return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
  1301. else:
  1302. return _handle_fromlist(module, fromlist, _gcd_import)
  1303. def _setup(sys_module, _imp_module):
  1304. """Setup importlib by importing needed built-in modules and injecting them
  1305. into the global namespace.
  1306. As sys is needed for sys.modules access and _imp is needed to load built-in
  1307. modules, those two modules must be explicitly passed in.
  1308. """
  1309. global _imp, sys
  1310. _imp = _imp_module
  1311. sys = sys_module
  1312. for module in (_imp, sys):
  1313. if not hasattr(module, '__loader__'):
  1314. module.__loader__ = BuiltinImporter
  1315. self_module = sys.modules[__name__]
  1316. for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'):
  1317. if builtin_name not in sys.modules:
  1318. builtin_module = BuiltinImporter.load_module(builtin_name)
  1319. else:
  1320. builtin_module = sys.modules[builtin_name]
  1321. setattr(self_module, builtin_name, builtin_module)
  1322. os_details = ('posix', ['/']), ('nt', ['\\', '/']), ('os2', ['\\', '/'])
  1323. for builtin_os, path_separators in os_details:
  1324. # Assumption made in _path_join()
  1325. assert all(len(sep) == 1 for sep in path_separators)
  1326. path_sep = path_separators[0]
  1327. if builtin_os in sys.modules:
  1328. os_module = sys.modules[builtin_os]
  1329. break
  1330. else:
  1331. try:
  1332. os_module = BuiltinImporter.load_module(builtin_os)
  1333. # TODO: rip out os2 code after 3.3 is released as per PEP 11
  1334. if builtin_os == 'os2' and 'EMX GCC' in sys.version:
  1335. path_sep = path_separators[1]
  1336. break
  1337. except ImportError:
  1338. continue
  1339. else:
  1340. raise ImportError('importlib requires posix or nt')
  1341. try:
  1342. thread_module = BuiltinImporter.load_module('_thread')
  1343. except ImportError:
  1344. # Python was built without threads
  1345. thread_module = None
  1346. weakref_module = BuiltinImporter.load_module('_weakref')
  1347. setattr(self_module, '_os', os_module)
  1348. setattr(self_module, '_thread', thread_module)
  1349. setattr(self_module, '_weakref', weakref_module)
  1350. setattr(self_module, 'path_sep', path_sep)
  1351. setattr(self_module, 'path_separators', set(path_separators))
  1352. # Constants
  1353. setattr(self_module, '_relax_case', _make_relax_case())
  1354. if builtin_os == 'nt':
  1355. SOURCE_SUFFIXES.append('.pyw')
  1356. def _install(sys_module, _imp_module):
  1357. """Install importlib as the implementation of import."""
  1358. _setup(sys_module, _imp_module)
  1359. extensions = ExtensionFileLoader, _imp_module.extension_suffixes(), False
  1360. source = SourceFileLoader, SOURCE_SUFFIXES, True
  1361. bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES, True
  1362. supported_loaders = [extensions, source, bytecode]
  1363. sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
  1364. sys.meta_path.extend([BuiltinImporter, FrozenImporter, PathFinder])