Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 77b2abd

Browse files
committed
Issue #15167 (as part of #13959): imp.get_magic() is no implemented in
Lib/imp.py.
1 parent afbb5fb commit 77b2abd

6 files changed

Lines changed: 3908 additions & 3906 deletions

File tree

Doc/c-api/import.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,10 @@ Importing Modules
172172
173173
Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and
174174
:file:`.pyo` files). The magic number should be present in the first four bytes
175-
of the bytecode file, in little-endian byte order.
175+
of the bytecode file, in little-endian byte order. Returns -1 on error.
176+
177+
.. versionchanged:: 3.3
178+
Return value of -1 upon failure.
176179
177180
178181
.. c:function:: const char * PyImport_GetMagicTag()

Doc/whatsnew/3.3.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1761,6 +1761,9 @@ Porting C code
17611761
:c:func:`PyUnicode_FromFormat()`, your code will automatically take
17621762
advantage of the new unicode representations.
17631763

1764+
* :c:func:`PyImport_GetMagicNumber` now returns -1 upon failure.
1765+
1766+
17641767
Building C extensions
17651768
---------------------
17661769

Lib/imp.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
load_dynamic, get_frozen_object, is_frozen_package,
1111
init_builtin, init_frozen, is_builtin, is_frozen,
1212
_fix_co_filename, extension_suffixes)
13-
# Could move out of _imp, but not worth the code
14-
from _imp import get_magic
1513

14+
# Directly exposed by this module
1615
from importlib._bootstrap import new_module
1716
from importlib._bootstrap import cache_from_source
1817

18+
1919
from importlib import _bootstrap
2020
from importlib import machinery
2121
import os
@@ -37,6 +37,11 @@
3737
IMP_HOOK = 9
3838

3939

40+
def get_magic():
41+
"""Return the magic number for .pyc or .pyo files."""
42+
return _bootstrap._MAGIC_BYTES
43+
44+
4045
def get_tag():
4146
"""Return the magic tag for .pyc or .pyo files."""
4247
return sys.implementation.cache_tag

Lib/importlib/_bootstrap.py

Lines changed: 92 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,96 @@ def _lock_unlock_module(name):
300300

301301
# Finder/loader utility code ##################################################
302302

303+
"""Magic word to reject .pyc files generated by other Python versions.
304+
It should change for each incompatible change to the bytecode.
305+
306+
The value of CR and LF is incorporated so if you ever read or write
307+
a .pyc file in text mode the magic number will be wrong; also, the
308+
Apple MPW compiler swaps their values, botching string constants.
309+
310+
The magic numbers must be spaced apart at least 2 values, as the
311+
-U interpeter flag will cause MAGIC+1 being used. They have been
312+
odd numbers for some time now.
313+
314+
There were a variety of old schemes for setting the magic number.
315+
The current working scheme is to increment the previous value by
316+
10.
317+
318+
Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
319+
number also includes a new "magic tag", i.e. a human readable string used
320+
to represent the magic number in __pycache__ directories. When you change
321+
the magic number, you must also set a new unique magic tag. Generally this
322+
can be named after the Python major version of the magic number bump, but
323+
it can really be anything, as long as it's different than anything else
324+
that's come before. The tags are included in the following table, starting
325+
with Python 3.2a0.
326+
327+
Known values:
328+
Python 1.5: 20121
329+
Python 1.5.1: 20121
330+
Python 1.5.2: 20121
331+
Python 1.6: 50428
332+
Python 2.0: 50823
333+
Python 2.0.1: 50823
334+
Python 2.1: 60202
335+
Python 2.1.1: 60202
336+
Python 2.1.2: 60202
337+
Python 2.2: 60717
338+
Python 2.3a0: 62011
339+
Python 2.3a0: 62021
340+
Python 2.3a0: 62011 (!)
341+
Python 2.4a0: 62041
342+
Python 2.4a3: 62051
343+
Python 2.4b1: 62061
344+
Python 2.5a0: 62071
345+
Python 2.5a0: 62081 (ast-branch)
346+
Python 2.5a0: 62091 (with)
347+
Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
348+
Python 2.5b3: 62101 (fix wrong code: for x, in ...)
349+
Python 2.5b3: 62111 (fix wrong code: x += yield)
350+
Python 2.5c1: 62121 (fix wrong lnotab with for loops and
351+
storing constants that should have been removed)
352+
Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
353+
Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
354+
Python 2.6a1: 62161 (WITH_CLEANUP optimization)
355+
Python 3000: 3000
356+
3010 (removed UNARY_CONVERT)
357+
3020 (added BUILD_SET)
358+
3030 (added keyword-only parameters)
359+
3040 (added signature annotations)
360+
3050 (print becomes a function)
361+
3060 (PEP 3115 metaclass syntax)
362+
3061 (string literals become unicode)
363+
3071 (PEP 3109 raise changes)
364+
3081 (PEP 3137 make __file__ and __name__ unicode)
365+
3091 (kill str8 interning)
366+
3101 (merge from 2.6a0, see 62151)
367+
3103 (__file__ points to source file)
368+
Python 3.0a4: 3111 (WITH_CLEANUP optimization).
369+
Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
370+
Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
371+
change LIST_APPEND and SET_ADD, add MAP_ADD)
372+
Python 3.1a0: 3151 (optimize conditional branches:
373+
introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
374+
Python 3.2a0: 3160 (add SETUP_WITH)
375+
tag: cpython-32
376+
Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
377+
tag: cpython-32
378+
Python 3.2a2 3180 (add DELETE_DEREF)
379+
Python 3.3a0 3190 __class__ super closure changed
380+
Python 3.3a0 3200 (__qualname__ added)
381+
3210 (added size modulo 2**32 to the pyc header)
382+
Python 3.3a1 3220 (changed PEP 380 implementation)
383+
Python 3.3a4 3230 (revert changes to implicit __class__ closure)
384+
385+
MAGIC must change whenever the bytecode emitted by the compiler may no
386+
longer be understood by older implementations of the eval loop (usually
387+
due to the addition of new opcodes).
388+
389+
"""
390+
_RAW_MAGIC_NUMBER = 3230 | ord('\r') << 16 | ord('\n') << 24
391+
_MAGIC_BYTES = bytes(_RAW_MAGIC_NUMBER >> n & 0xff for n in range(0, 25, 8))
392+
303393
_PYCACHE = '__pycache__'
304394

305395
SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
@@ -611,7 +701,7 @@ def _bytes_from_bytecode(self, fullname, data, bytecode_path, source_stats):
611701
magic = data[:4]
612702
raw_timestamp = data[4:8]
613703
raw_size = data[8:12]
614-
if magic != _MAGIC_NUMBER:
704+
if magic != _MAGIC_BYTES:
615705
msg = 'bad magic number in {!r}: {!r}'.format(fullname, magic)
616706
raise ImportError(msg, name=fullname, path=bytecode_path)
617707
elif len(raw_timestamp) != 4:
@@ -768,7 +858,7 @@ def get_code(self, fullname):
768858
_verbose_message('code object from {}', source_path)
769859
if (not sys.dont_write_bytecode and bytecode_path is not None and
770860
source_mtime is not None):
771-
data = bytearray(_MAGIC_NUMBER)
861+
data = bytearray(_MAGIC_BYTES)
772862
data.extend(_w_long(source_mtime))
773863
data.extend(_w_long(len(source_bytes)))
774864
data.extend(marshal.dumps(code_object))
@@ -1427,8 +1517,6 @@ def __import__(name, globals={}, locals={}, fromlist=[], level=0):
14271517
return _handle_fromlist(module, fromlist, _gcd_import)
14281518

14291519

1430-
_MAGIC_NUMBER = None # Set in _setup()
1431-
14321520

14331521
def _setup(sys_module, _imp_module):
14341522
"""Setup importlib by importing needed built-in modules and injecting them
@@ -1488,7 +1576,6 @@ def _setup(sys_module, _imp_module):
14881576
setattr(self_module, 'path_separators', set(path_separators))
14891577
# Constants
14901578
setattr(self_module, '_relax_case', _make_relax_case())
1491-
setattr(self_module, '_MAGIC_NUMBER', _imp_module.get_magic())
14921579
if builtin_os == 'nt':
14931580
SOURCE_SUFFIXES.append('.pyw')
14941581

Python/import.c

Lines changed: 6 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -27,97 +27,7 @@ typedef unsigned short mode_t;
2727
#endif
2828

2929

30-
/* Magic word to reject .pyc files generated by other Python versions.
31-
It should change for each incompatible change to the bytecode.
32-
33-
The value of CR and LF is incorporated so if you ever read or write
34-
a .pyc file in text mode the magic number will be wrong; also, the
35-
Apple MPW compiler swaps their values, botching string constants.
36-
37-
The magic numbers must be spaced apart at least 2 values, as the
38-
-U interpeter flag will cause MAGIC+1 being used. They have been
39-
odd numbers for some time now.
40-
41-
There were a variety of old schemes for setting the magic number.
42-
The current working scheme is to increment the previous value by
43-
10.
44-
45-
Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
46-
number also includes a new "magic tag", i.e. a human readable string used
47-
to represent the magic number in __pycache__ directories. When you change
48-
the magic number, you must also set a new unique magic tag. Generally this
49-
can be named after the Python major version of the magic number bump, but
50-
it can really be anything, as long as it's different than anything else
51-
that's come before. The tags are included in the following table, starting
52-
with Python 3.2a0.
53-
54-
Known values:
55-
Python 1.5: 20121
56-
Python 1.5.1: 20121
57-
Python 1.5.2: 20121
58-
Python 1.6: 50428
59-
Python 2.0: 50823
60-
Python 2.0.1: 50823
61-
Python 2.1: 60202
62-
Python 2.1.1: 60202
63-
Python 2.1.2: 60202
64-
Python 2.2: 60717
65-
Python 2.3a0: 62011
66-
Python 2.3a0: 62021
67-
Python 2.3a0: 62011 (!)
68-
Python 2.4a0: 62041
69-
Python 2.4a3: 62051
70-
Python 2.4b1: 62061
71-
Python 2.5a0: 62071
72-
Python 2.5a0: 62081 (ast-branch)
73-
Python 2.5a0: 62091 (with)
74-
Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
75-
Python 2.5b3: 62101 (fix wrong code: for x, in ...)
76-
Python 2.5b3: 62111 (fix wrong code: x += yield)
77-
Python 2.5c1: 62121 (fix wrong lnotab with for loops and
78-
storing constants that should have been removed)
79-
Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
80-
Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
81-
Python 2.6a1: 62161 (WITH_CLEANUP optimization)
82-
Python 3000: 3000
83-
3010 (removed UNARY_CONVERT)
84-
3020 (added BUILD_SET)
85-
3030 (added keyword-only parameters)
86-
3040 (added signature annotations)
87-
3050 (print becomes a function)
88-
3060 (PEP 3115 metaclass syntax)
89-
3061 (string literals become unicode)
90-
3071 (PEP 3109 raise changes)
91-
3081 (PEP 3137 make __file__ and __name__ unicode)
92-
3091 (kill str8 interning)
93-
3101 (merge from 2.6a0, see 62151)
94-
3103 (__file__ points to source file)
95-
Python 3.0a4: 3111 (WITH_CLEANUP optimization).
96-
Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
97-
Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
98-
change LIST_APPEND and SET_ADD, add MAP_ADD)
99-
Python 3.1a0: 3151 (optimize conditional branches:
100-
introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
101-
Python 3.2a0: 3160 (add SETUP_WITH)
102-
tag: cpython-32
103-
Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
104-
tag: cpython-32
105-
Python 3.2a2 3180 (add DELETE_DEREF)
106-
Python 3.3a0 3190 __class__ super closure changed
107-
Python 3.3a0 3200 (__qualname__ added)
108-
3210 (added size modulo 2**32 to the pyc header)
109-
Python 3.3a1 3220 (changed PEP 380 implementation)
110-
Python 3.3a4 3230 (revert changes to implicit __class__ closure)
111-
*/
112-
113-
/* MAGIC must change whenever the bytecode emitted by the compiler may no
114-
longer be understood by older implementations of the eval loop (usually
115-
due to the addition of new opcodes)
116-
*/
117-
#define MAGIC (3230 | ((long)'\r'<<16) | ((long)'\n'<<24))
11830
#define CACHEDIR "__pycache__"
119-
/* Current magic word as global. */
120-
static long pyc_magic = MAGIC;
12131

12232
/* See _PyImport_FixupExtensionObject() below */
12333
static PyObject *extensions = NULL;
@@ -516,7 +426,12 @@ PyImport_Cleanup(void)
516426
long
517427
PyImport_GetMagicNumber(void)
518428
{
519-
return pyc_magic;
429+
PyInterpreterState *interp = PyThreadState_Get()->interp;
430+
PyObject *pyc_magic = PyObject_GetAttrString(interp->importlib,
431+
"_RAW_MAGIC_NUMBER");
432+
if (pyc_magic == NULL)
433+
return -1;
434+
return PyLong_AsLong(pyc_magic);
520435
}
521436

522437

@@ -1879,30 +1794,6 @@ PyImport_Import(PyObject *module_name)
18791794
return r;
18801795
}
18811796

1882-
1883-
/* Module 'imp' provides Python access to the primitives used for
1884-
importing modules.
1885-
*/
1886-
1887-
static PyObject *
1888-
imp_make_magic(long magic)
1889-
{
1890-
char buf[4];
1891-
1892-
buf[0] = (char) ((magic >> 0) & 0xff);
1893-
buf[1] = (char) ((magic >> 8) & 0xff);
1894-
buf[2] = (char) ((magic >> 16) & 0xff);
1895-
buf[3] = (char) ((magic >> 24) & 0xff);
1896-
1897-
return PyBytes_FromStringAndSize(buf, 4);
1898-
}
1899-
1900-
static PyObject *
1901-
imp_get_magic(PyObject *self, PyObject *noargs)
1902-
{
1903-
return imp_make_magic(pyc_magic);
1904-
}
1905-
19061797
static PyObject *
19071798
imp_extension_suffixes(PyObject *self, PyObject *noargs)
19081799
{
@@ -2049,10 +1940,6 @@ imp_load_dynamic(PyObject *self, PyObject *args)
20491940
PyDoc_STRVAR(doc_imp,
20501941
"(Extremely) low-level import machinery bits as used by importlib and imp.");
20511942

2052-
PyDoc_STRVAR(doc_get_magic,
2053-
"get_magic() -> string\n\
2054-
Return the magic number for .pyc or .pyo files.");
2055-
20561943
PyDoc_STRVAR(doc_extension_suffixes,
20571944
"extension_suffixes() -> list of strings\n\
20581945
Returns the list of file suffixes used to identify extension modules.");
@@ -2075,7 +1962,6 @@ Release the interpreter's import lock.\n\
20751962
On platforms without threads, this function does nothing.");
20761963

20771964
static PyMethodDef imp_methods[] = {
2078-
{"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
20791965
{"extension_suffixes", imp_extension_suffixes, METH_NOARGS,
20801966
doc_extension_suffixes},
20811967
{"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},

0 commit comments

Comments
 (0)