Issue #12467: warnings: fix a race condition if a warning is emitted at
shutdown, if globals()['__file__'] is None.
diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py
index dbf30e9..79be835 100644
--- a/Lib/test/test_warnings.py
+++ b/Lib/test/test_warnings.py
@@ -542,6 +542,18 @@
         assert expected_line
         self.assertEqual(second_line, expected_line)
 
+    def test_filename_none(self):
+        # issue #12467: race condition if a warning is emitted at shutdown
+        globals_dict = globals()
+        oldfile = globals_dict['__file__']
+        try:
+            with original_warnings.catch_warnings(module=self.module) as w:
+                self.module.filterwarnings("always", category=UserWarning)
+                globals_dict['__file__'] = None
+                original_warnings.warn('test', UserWarning)
+        finally:
+            globals_dict['__file__'] = oldfile
+
 
 class WarningsDisplayTests(unittest.TestCase):
 
diff --git a/Misc/NEWS b/Misc/NEWS
index 5d4ed6f..401a8ea 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -19,6 +19,9 @@
 Library
 -------
 
+- Issue #12467: warnings: fix a race condition if a warning is emitted at
+  shutdown, if globals()['__file__'] is None.
+
 - Issue #12451: pydoc: importfile() now opens the Python script in binary mode,
   instead of text mode using the locale encoding, to avoid encoding issues.
 
diff --git a/Python/_warnings.c b/Python/_warnings.c
index a797887..07fd683 100644
--- a/Python/_warnings.c
+++ b/Python/_warnings.c
@@ -496,7 +496,7 @@
 
     /* Setup filename. */
     *filename = PyDict_GetItemString(globals, "__file__");
-    if (*filename != NULL) {
+    if (*filename != NULL && PyUnicode_Check(*filename)) {
         Py_ssize_t len = PyUnicode_GetSize(*filename);
         Py_UNICODE *unicode = PyUnicode_AS_UNICODE(*filename);