[3.6] bpo-31393: Fix the use of PyUnicode_READY(). (GH-3451). (#3453)

(cherry picked from commit e3b2b4b8d9e751b49e3550cb83ba39b54fdc377c)
diff --git a/Objects/codeobject.c b/Objects/codeobject.c
index 6de697a..d45be4c 100644
--- a/Objects/codeobject.c
+++ b/Objects/codeobject.c
@@ -22,8 +22,7 @@
     static const unsigned char *name_chars = (unsigned char *)NAME_CHARS;
     const unsigned char *s, *e;
 
-    if (!PyUnicode_Check(o) || PyUnicode_READY(o) == -1 ||
-        !PyUnicode_IS_ASCII(o))
+    if (!PyUnicode_IS_ASCII(o))
         return 0;
 
     if (ok_name_char[*name_chars] == 0) {
@@ -64,6 +63,10 @@
     for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
         PyObject *v = PyTuple_GET_ITEM(tuple, i);
         if (PyUnicode_CheckExact(v)) {
+            if (PyUnicode_READY(v) == -1) {
+                PyErr_Clear();
+                continue;
+            }
             if (all_name_chars(v)) {
                 PyObject *w = v;
                 PyUnicode_InternInPlace(&v);
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index 271b935..cb5e235 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -22,9 +22,9 @@
 #define MCACHE_HASH_METHOD(type, name)                                  \
         MCACHE_HASH((type)->tp_version_tag,                     \
                     ((PyASCIIObject *)(name))->hash)
-#define MCACHE_CACHEABLE_NAME(name)                                     \
-        PyUnicode_CheckExact(name) &&                            \
-        PyUnicode_READY(name) != -1 &&                      \
+#define MCACHE_CACHEABLE_NAME(name)                             \
+        PyUnicode_CheckExact(name) &&                           \
+        PyUnicode_IS_READY(name) &&                             \
         PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE
 
 struct method_cache_entry {
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index 1650370..1f221af 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -4210,10 +4210,13 @@
     void *data;
     int kind;
 
-    if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
+    if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
         return (Py_UCS4)-1;
     }
+    if (PyUnicode_READY(unicode) == -1) {
+        return (Py_UCS4)-1;
+    }
     if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
         PyErr_SetString(PyExc_IndexError, "string index out of range");
         return (Py_UCS4)-1;
@@ -11706,10 +11709,13 @@
     enum PyUnicode_Kind kind;
     Py_UCS4 ch;
 
-    if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
+    if (!PyUnicode_Check(self)) {
         PyErr_BadArgument();
         return NULL;
     }
+    if (PyUnicode_READY(self) == -1) {
+        return NULL;
+    }
     if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
         PyErr_SetString(PyExc_IndexError, "string index out of range");
         return NULL;