1:mod:`winreg` --- Windows registry access
2=========================================
3
4.. module:: winreg
5   :platform: Windows
6   :synopsis: Routines and objects for manipulating the Windows registry.
7
8.. sectionauthor:: Mark Hammond <[email protected]>
9
10--------------
11
12These functions expose the Windows registry API to Python.  Instead of using an
13integer as the registry handle, a :ref:`handle object <handle-object>` is used
14to ensure that the handles are closed correctly, even if the programmer neglects
15to explicitly close them.
16
17.. _exception-changed:
18
19.. versionchanged:: 3.3
20   Several functions in this module used to raise a
21   :exc:`WindowsError`, which is now an alias of :exc:`OSError`.
22
23.. _functions:
24
25Functions
26------------------
27
28This module offers the following functions:
29
30
31.. function:: CloseKey(hkey)
32
33   Closes a previously opened registry key.  The *hkey* argument specifies a
34   previously opened key.
35
36   .. note::
37
38      If *hkey* is not closed using this method (or via :meth:`hkey.Close()
39      <PyHKEY.Close>`), it is closed when the *hkey* object is destroyed by
40      Python.
41
42
43.. function:: ConnectRegistry(computer_name, key)
44
45   Establishes a connection to a predefined registry handle on another computer,
46   and returns a :ref:`handle object <handle-object>`.
47
48   *computer_name* is the name of the remote computer, of the form
49   ``r"\\computername"``.  If ``None``, the local computer is used.
50
51   *key* is the predefined handle to connect to.
52
53   The return value is the handle of the opened key. If the function fails, an
54   :exc:`OSError` exception is raised.
55
56   .. audit-event:: winreg.ConnectRegistry computer_name,key winreg.ConnectRegistry
57
58   .. versionchanged:: 3.3
59      See :ref:`above <exception-changed>`.
60
61
62.. function:: CreateKey(key, sub_key)
63
64   Creates or opens the specified key, returning a
65   :ref:`handle object <handle-object>`.
66
67   *key* is an already open key, or one of the predefined
68   :ref:`HKEY_* constants <hkey-constants>`.
69
70   *sub_key* is a string that names the key this method opens or creates.
71
72   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
73   case, the handle returned is the same key handle passed in to the function.
74
75   If the key already exists, this function opens the existing key.
76
77   The return value is the handle of the opened key. If the function fails, an
78   :exc:`OSError` exception is raised.
79
80   .. audit-event:: winreg.CreateKey key,sub_key,access winreg.CreateKey
81
82   .. audit-event:: winreg.OpenKey/result key winreg.CreateKey
83
84   .. versionchanged:: 3.3
85      See :ref:`above <exception-changed>`.
86
87
88.. function:: CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)
89
90   Creates or opens the specified key, returning a
91   :ref:`handle object <handle-object>`.
92
93   *key* is an already open key, or one of the predefined
94   :ref:`HKEY_* constants <hkey-constants>`.
95
96   *sub_key* is a string that names the key this method opens or creates.
97
98   *reserved* is a reserved integer, and must be zero. The default is zero.
99
100   *access* is an integer that specifies an access mask that describes the desired
101   security access for the key.  Default is :const:`KEY_WRITE`.  See
102   :ref:`Access Rights <access-rights>` for other allowed values.
103
104   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
105   case, the handle returned is the same key handle passed in to the function.
106
107   If the key already exists, this function opens the existing key.
108
109   The return value is the handle of the opened key. If the function fails, an
110   :exc:`OSError` exception is raised.
111
112   .. audit-event:: winreg.CreateKey key,sub_key,access winreg.CreateKeyEx
113
114   .. audit-event:: winreg.OpenKey/result key winreg.CreateKeyEx
115
116   .. versionadded:: 3.2
117
118   .. versionchanged:: 3.3
119      See :ref:`above <exception-changed>`.
120
121
122.. function:: DeleteKey(key, sub_key)
123
124   Deletes the specified key.
125
126   *key* is an already open key, or one of the predefined
127   :ref:`HKEY_* constants <hkey-constants>`.
128
129   *sub_key* is a string that must be a subkey of the key identified by the *key*
130   parameter.  This value must not be ``None``, and the key may not have subkeys.
131
132   *This method can not delete keys with subkeys.*
133
134   If the method succeeds, the entire key, including all of its values, is removed.
135   If the method fails, an :exc:`OSError` exception is raised.
136
137   .. audit-event:: winreg.DeleteKey key,sub_key,access winreg.DeleteKey
138
139   .. versionchanged:: 3.3
140      See :ref:`above <exception-changed>`.
141
142
143.. function:: DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)
144
145   Deletes the specified key.
146
147   *key* is an already open key, or one of the predefined
148   :ref:`HKEY_* constants <hkey-constants>`.
149
150   *sub_key* is a string that must be a subkey of the key identified by the
151   *key* parameter. This value must not be ``None``, and the key may not have
152   subkeys.
153
154   *reserved* is a reserved integer, and must be zero. The default is zero.
155
156   *access* is an integer that specifies an access mask that describes the
157   desired security access for the key.  Default is :const:`KEY_WOW64_64KEY`.
158   On 32-bit Windows, the WOW64 constants are ignored.
159   See :ref:`Access Rights <access-rights>` for other allowed values.
160
161   *This method can not delete keys with subkeys.*
162
163   If the method succeeds, the entire key, including all of its values, is
164   removed. If the method fails, an :exc:`OSError` exception is raised.
165
166   On unsupported Windows versions, :exc:`NotImplementedError` is raised.
167
168   .. audit-event:: winreg.DeleteKey key,sub_key,access winreg.DeleteKeyEx
169
170   .. versionadded:: 3.2
171
172   .. versionchanged:: 3.3
173      See :ref:`above <exception-changed>`.
174
175
176.. function:: DeleteValue(key, value)
177
178   Removes a named value from a registry key.
179
180   *key* is an already open key, or one of the predefined
181   :ref:`HKEY_* constants <hkey-constants>`.
182
183   *value* is a string that identifies the value to remove.
184
185   .. audit-event:: winreg.DeleteValue key,value winreg.DeleteValue
186
187
188.. function:: EnumKey(key, index)
189
190   Enumerates subkeys of an open registry key, returning a string.
191
192   *key* is an already open key, or one of the predefined
193   :ref:`HKEY_* constants <hkey-constants>`.
194
195   *index* is an integer that identifies the index of the key to retrieve.
196
197   The function retrieves the name of one subkey each time it is called.  It is
198   typically called repeatedly until an :exc:`OSError` exception is
199   raised, indicating, no more values are available.
200
201   .. audit-event:: winreg.EnumKey key,index winreg.EnumKey
202
203   .. versionchanged:: 3.3
204      See :ref:`above <exception-changed>`.
205
206
207.. function:: EnumValue(key, index)
208
209   Enumerates values of an open registry key, returning a tuple.
210
211   *key* is an already open key, or one of the predefined
212   :ref:`HKEY_* constants <hkey-constants>`.
213
214   *index* is an integer that identifies the index of the value to retrieve.
215
216   The function retrieves the name of one subkey each time it is called. It is
217   typically called repeatedly, until an :exc:`OSError` exception is
218   raised, indicating no more values.
219
220   The result is a tuple of 3 items:
221
222   +-------+--------------------------------------------+
223   | Index | Meaning                                    |
224   +=======+============================================+
225   | ``0`` | A string that identifies the value name    |
226   +-------+--------------------------------------------+
227   | ``1`` | An object that holds the value data, and   |
228   |       | whose type depends on the underlying       |
229   |       | registry type                              |
230   +-------+--------------------------------------------+
231   | ``2`` | An integer that identifies the type of the |
232   |       | value data (see table in docs for          |
233   |       | :meth:`SetValueEx`)                        |
234   +-------+--------------------------------------------+
235
236   .. audit-event:: winreg.EnumValue key,index winreg.EnumValue
237
238   .. versionchanged:: 3.3
239      See :ref:`above <exception-changed>`.
240
241
242.. index::
243   single: % (percent); environment variables expansion (Windows)
244
245.. function:: ExpandEnvironmentStrings(str)
246
247   Expands environment variable placeholders ``%NAME%`` in strings like
248   :const:`REG_EXPAND_SZ`::
249
250      >>> ExpandEnvironmentStrings('%windir%')
251      'C:\\Windows'
252
253   .. audit-event:: winreg.ExpandEnvironmentStrings str winreg.ExpandEnvironmentStrings
254
255
256.. function:: FlushKey(key)
257
258   Writes all the attributes of a key to the registry.
259
260   *key* is an already open key, or one of the predefined
261   :ref:`HKEY_* constants <hkey-constants>`.
262
263   It is not necessary to call :func:`FlushKey` to change a key. Registry changes are
264   flushed to disk by the registry using its lazy flusher.  Registry changes are
265   also flushed to disk at system shutdown.  Unlike :func:`CloseKey`, the
266   :func:`FlushKey` method returns only when all the data has been written to the
267   registry. An application should only call :func:`FlushKey` if it requires
268   absolute certainty that registry changes are on disk.
269
270   .. note::
271
272      If you don't know whether a :func:`FlushKey` call is required, it probably
273      isn't.
274
275
276.. function:: LoadKey(key, sub_key, file_name)
277
278   Creates a subkey under the specified key and stores registration information
279   from a specified file into that subkey.
280
281   *key* is a handle returned by :func:`ConnectRegistry` or one of the constants
282   :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`.
283
284   *sub_key* is a string that identifies the subkey to load.
285
286   *file_name* is the name of the file to load registry data from. This file must
287   have been created with the :func:`SaveKey` function. Under the file allocation
288   table (FAT) file system, the filename may not have an extension.
289
290   A call to :func:`LoadKey` fails if the calling process does not have the
291   :const:`SE_RESTORE_PRIVILEGE` privilege.  Note that privileges are different
292   from permissions -- see the `RegLoadKey documentation
293   <https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx>`__ for
294   more details.
295
296   If *key* is a handle returned by :func:`ConnectRegistry`, then the path
297   specified in *file_name* is relative to the remote computer.
298
299   .. audit-event:: winreg.LoadKey key,sub_key,file_name winreg.LoadKey
300
301
302.. function:: OpenKey(key, sub_key, reserved=0, access=KEY_READ)
303              OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ)
304
305   Opens the specified key, returning a :ref:`handle object <handle-object>`.
306
307   *key* is an already open key, or one of the predefined
308   :ref:`HKEY_* constants <hkey-constants>`.
309
310   *sub_key* is a string that identifies the sub_key to open.
311
312   *reserved* is a reserved integer, and must be zero.  The default is zero.
313
314   *access* is an integer that specifies an access mask that describes the desired
315   security access for the key.  Default is :const:`KEY_READ`.  See :ref:`Access
316   Rights <access-rights>` for other allowed values.
317
318   The result is a new handle to the specified key.
319
320   If the function fails, :exc:`OSError` is raised.
321
322   .. audit-event:: winreg.OpenKey key,sub_key,access winreg.OpenKey
323
324   .. audit-event:: winreg.OpenKey/result key winreg.OpenKey
325
326   .. versionchanged:: 3.2
327      Allow the use of named arguments.
328
329   .. versionchanged:: 3.3
330      See :ref:`above <exception-changed>`.
331
332
333.. function:: QueryInfoKey(key)
334
335   Returns information about a key, as a tuple.
336
337   *key* is an already open key, or one of the predefined
338   :ref:`HKEY_* constants <hkey-constants>`.
339
340   The result is a tuple of 3 items:
341
342   +-------+---------------------------------------------+
343   | Index | Meaning                                     |
344   +=======+=============================================+
345   | ``0`` | An integer giving the number of sub keys    |
346   |       | this key has.                               |
347   +-------+---------------------------------------------+
348   | ``1`` | An integer giving the number of values this |
349   |       | key has.                                    |
350   +-------+---------------------------------------------+
351   | ``2`` | An integer giving when the key was last     |
352   |       | modified (if available) as 100's of         |
353   |       | nanoseconds since Jan 1, 1601.              |
354   +-------+---------------------------------------------+
355
356   .. audit-event:: winreg.QueryInfoKey key winreg.QueryInfoKey
357
358
359.. function:: QueryValue(key, sub_key)
360
361   Retrieves the unnamed value for a key, as a string.
362
363   *key* is an already open key, or one of the predefined
364   :ref:`HKEY_* constants <hkey-constants>`.
365
366   *sub_key* is a string that holds the name of the subkey with which the value is
367   associated.  If this parameter is ``None`` or empty, the function retrieves the
368   value set by the :func:`SetValue` method for the key identified by *key*.
369
370   Values in the registry have name, type, and data components. This method
371   retrieves the data for a key's first value that has a ``NULL`` name. But the
372   underlying API call doesn't return the type, so always use
373   :func:`QueryValueEx` if possible.
374
375   .. audit-event:: winreg.QueryValue key,sub_key,value_name winreg.QueryValue
376
377
378.. function:: QueryValueEx(key, value_name)
379
380   Retrieves the type and data for a specified value name associated with
381   an open registry key.
382
383   *key* is an already open key, or one of the predefined
384   :ref:`HKEY_* constants <hkey-constants>`.
385
386   *value_name* is a string indicating the value to query.
387
388   The result is a tuple of 2 items:
389
390   +-------+-----------------------------------------+
391   | Index | Meaning                                 |
392   +=======+=========================================+
393   | ``0`` | The value of the registry item.         |
394   +-------+-----------------------------------------+
395   | ``1`` | An integer giving the registry type for |
396   |       | this value (see table in docs for       |
397   |       | :meth:`SetValueEx`)                     |
398   +-------+-----------------------------------------+
399
400   .. audit-event:: winreg.QueryValue key,sub_key,value_name winreg.QueryValueEx
401
402
403.. function:: SaveKey(key, file_name)
404
405   Saves the specified key, and all its subkeys to the specified file.
406
407   *key* is an already open key, or one of the predefined
408   :ref:`HKEY_* constants <hkey-constants>`.
409
410   *file_name* is the name of the file to save registry data to.  This file
411   cannot already exist. If this filename includes an extension, it cannot be
412   used on file allocation table (FAT) file systems by the :meth:`LoadKey`
413   method.
414
415   If *key* represents a key on a remote computer, the path described by
416   *file_name* is relative to the remote computer. The caller of this method must
417   possess the :const:`SeBackupPrivilege` security privilege.  Note that
418   privileges are different than permissions -- see the
419   `Conflicts Between User Rights and Permissions documentation
420   <https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__
421   for more details.
422
423   This function passes ``NULL`` for *security_attributes* to the API.
424
425   .. audit-event:: winreg.SaveKey key,file_name winreg.SaveKey
426
427
428.. function:: SetValue(key, sub_key, type, value)
429
430   Associates a value with a specified key.
431
432   *key* is an already open key, or one of the predefined
433   :ref:`HKEY_* constants <hkey-constants>`.
434
435   *sub_key* is a string that names the subkey with which the value is associated.
436
437   *type* is an integer that specifies the type of the data. Currently this must be
438   :const:`REG_SZ`, meaning only strings are supported.  Use the :func:`SetValueEx`
439   function for support for other data types.
440
441   *value* is a string that specifies the new value.
442
443   If the key specified by the *sub_key* parameter does not exist, the SetValue
444   function creates it.
445
446   Value lengths are limited by available memory. Long values (more than 2048
447   bytes) should be stored as files with the filenames stored in the configuration
448   registry.  This helps the registry perform efficiently.
449
450   The key identified by the *key* parameter must have been opened with
451   :const:`KEY_SET_VALUE` access.
452
453   .. audit-event:: winreg.SetValue key,sub_key,type,value winreg.SetValue
454
455
456.. function:: SetValueEx(key, value_name, reserved, type, value)
457
458   Stores data in the value field of an open registry key.
459
460   *key* is an already open key, or one of the predefined
461   :ref:`HKEY_* constants <hkey-constants>`.
462
463   *value_name* is a string that names the subkey with which the value is
464   associated.
465
466   *reserved* can be anything -- zero is always passed to the API.
467
468   *type* is an integer that specifies the type of the data. See
469   :ref:`Value Types <value-types>` for the available types.
470
471   *value* is a string that specifies the new value.
472
473   This method can also set additional value and type information for the specified
474   key.  The key identified by the key parameter must have been opened with
475   :const:`KEY_SET_VALUE` access.
476
477   To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods.
478
479   Value lengths are limited by available memory. Long values (more than 2048
480   bytes) should be stored as files with the filenames stored in the configuration
481   registry.  This helps the registry perform efficiently.
482
483   .. audit-event:: winreg.SetValue key,sub_key,type,value winreg.SetValueEx
484
485
486.. function:: DisableReflectionKey(key)
487
488   Disables registry reflection for 32-bit processes running on a 64-bit
489   operating system.
490
491   *key* is an already open key, or one of the predefined :ref:`HKEY_* constants
492   <hkey-constants>`.
493
494   Will generally raise :exc:`NotImplementedError` if executed on a 32-bit operating
495   system.
496
497   If the key is not on the reflection list, the function succeeds but has no
498   effect.  Disabling reflection for a key does not affect reflection of any
499   subkeys.
500
501   .. audit-event:: winreg.DisableReflectionKey key winreg.DisableReflectionKey
502
503
504.. function:: EnableReflectionKey(key)
505
506   Restores registry reflection for the specified disabled key.
507
508   *key* is an already open key, or one of the predefined :ref:`HKEY_* constants
509   <hkey-constants>`.
510
511   Will generally raise :exc:`NotImplementedError` if executed on a 32-bit operating
512   system.
513
514   Restoring reflection for a key does not affect reflection of any subkeys.
515
516   .. audit-event:: winreg.EnableReflectionKey key winreg.EnableReflectionKey
517
518
519.. function:: QueryReflectionKey(key)
520
521   Determines the reflection state for the specified key.
522
523   *key* is an already open key, or one of the predefined
524   :ref:`HKEY_* constants <hkey-constants>`.
525
526   Returns ``True`` if reflection is disabled.
527
528   Will generally raise :exc:`NotImplementedError` if executed on a 32-bit
529   operating system.
530
531   .. audit-event:: winreg.QueryReflectionKey key winreg.QueryReflectionKey
532
533
534.. _constants:
535
536Constants
537------------------
538
539The following constants are defined for use in many :mod:`_winreg` functions.
540
541.. _hkey-constants:
542
543HKEY_* Constants
544++++++++++++++++
545
546.. data:: HKEY_CLASSES_ROOT
547
548   Registry entries subordinate to this key define types (or classes) of
549   documents and the properties associated with those types. Shell and
550   COM applications use the information stored under this key.
551
552
553.. data:: HKEY_CURRENT_USER
554
555   Registry entries subordinate to this key define the preferences of
556   the current user. These preferences include the settings of
557   environment variables, data about program groups, colors, printers,
558   network connections, and application preferences.
559
560.. data:: HKEY_LOCAL_MACHINE
561
562   Registry entries subordinate to this key define the physical state
563   of the computer, including data about the bus type, system memory,
564   and installed hardware and software.
565
566.. data:: HKEY_USERS
567
568   Registry entries subordinate to this key define the default user
569   configuration for new users on the local computer and the user
570   configuration for the current user.
571
572.. data:: HKEY_PERFORMANCE_DATA
573
574   Registry entries subordinate to this key allow you to access
575   performance data. The data is not actually stored in the registry;
576   the registry functions cause the system to collect the data from
577   its source.
578
579
580.. data:: HKEY_CURRENT_CONFIG
581
582   Contains information about the current hardware profile of the
583   local computer system.
584
585.. data:: HKEY_DYN_DATA
586
587   This key is not used in versions of Windows after 98.
588
589
590.. _access-rights:
591
592Access Rights
593+++++++++++++
594
595For more information, see `Registry Key Security and Access
596<https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__.
597
598.. data:: KEY_ALL_ACCESS
599
600   Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`,
601   :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`,
602   :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`,
603   and :const:`KEY_CREATE_LINK` access rights.
604
605.. data:: KEY_WRITE
606
607   Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and
608   :const:`KEY_CREATE_SUB_KEY` access rights.
609
610.. data:: KEY_READ
611
612   Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`,
613   :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values.
614
615.. data:: KEY_EXECUTE
616
617   Equivalent to :const:`KEY_READ`.
618
619.. data:: KEY_QUERY_VALUE
620
621   Required to query the values of a registry key.
622
623.. data:: KEY_SET_VALUE
624
625   Required to create, delete, or set a registry value.
626
627.. data:: KEY_CREATE_SUB_KEY
628
629   Required to create a subkey of a registry key.
630
631.. data:: KEY_ENUMERATE_SUB_KEYS
632
633   Required to enumerate the subkeys of a registry key.
634
635.. data:: KEY_NOTIFY
636
637   Required to request change notifications for a registry key or for
638   subkeys of a registry key.
639
640.. data:: KEY_CREATE_LINK
641
642   Reserved for system use.
643
644
645.. _64-bit-access-rights:
646
64764-bit Specific
648***************
649
650For more information, see `Accessing an Alternate Registry View
651<https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx>`__.
652
653.. data:: KEY_WOW64_64KEY
654
655   Indicates that an application on 64-bit Windows should operate on
656   the 64-bit registry view. On 32-bit Windows, this constant is ignored.
657
658.. data:: KEY_WOW64_32KEY
659
660   Indicates that an application on 64-bit Windows should operate on
661   the 32-bit registry view. On 32-bit Windows, this constant is ignored.
662
663.. _value-types:
664
665Value Types
666+++++++++++
667
668For more information, see `Registry Value Types
669<https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx>`__.
670
671.. data:: REG_BINARY
672
673   Binary data in any form.
674
675.. data:: REG_DWORD
676
677   32-bit number.
678
679.. data:: REG_DWORD_LITTLE_ENDIAN
680
681   A 32-bit number in little-endian format. Equivalent to :const:`REG_DWORD`.
682
683.. data:: REG_DWORD_BIG_ENDIAN
684
685   A 32-bit number in big-endian format.
686
687.. data:: REG_EXPAND_SZ
688
689   Null-terminated string containing references to environment
690   variables (``%PATH%``).
691
692.. data:: REG_LINK
693
694   A Unicode symbolic link.
695
696.. data:: REG_MULTI_SZ
697
698   A sequence of null-terminated strings, terminated by two null characters.
699   (Python handles this termination automatically.)
700
701.. data:: REG_NONE
702
703   No defined value type.
704
705.. data:: REG_QWORD
706
707   A 64-bit number.
708
709   .. versionadded:: 3.6
710
711.. data:: REG_QWORD_LITTLE_ENDIAN
712
713   A 64-bit number in little-endian format. Equivalent to :const:`REG_QWORD`.
714
715   .. versionadded:: 3.6
716
717.. data:: REG_RESOURCE_LIST
718
719   A device-driver resource list.
720
721.. data:: REG_FULL_RESOURCE_DESCRIPTOR
722
723   A hardware setting.
724
725.. data:: REG_RESOURCE_REQUIREMENTS_LIST
726
727   A hardware resource list.
728
729.. data:: REG_SZ
730
731   A null-terminated string.
732
733
734.. _handle-object:
735
736Registry Handle Objects
737-----------------------
738
739This object wraps a Windows HKEY object, automatically closing it when the
740object is destroyed.  To guarantee cleanup, you can call either the
741:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function.
742
743All registry functions in this module return one of these objects.
744
745All registry functions in this module which accept a handle object also accept
746an integer, however, use of the handle object is encouraged.
747
748Handle objects provide semantics for :meth:`__bool__` -- thus ::
749
750   if handle:
751       print("Yes")
752
753will print ``Yes`` if the handle is currently valid (has not been closed or
754detached).
755
756The object also support comparison semantics, so handle objects will compare
757true if they both reference the same underlying Windows handle value.
758
759Handle objects can be converted to an integer (e.g., using the built-in
760:func:`int` function), in which case the underlying Windows handle value is
761returned.  You can also use the :meth:`~PyHKEY.Detach` method to return the
762integer handle, and also disconnect the Windows handle from the handle object.
763
764
765.. method:: PyHKEY.Close()
766
767   Closes the underlying Windows handle.
768
769   If the handle is already closed, no error is raised.
770
771
772.. method:: PyHKEY.Detach()
773
774   Detaches the Windows handle from the handle object.
775
776   The result is an integer that holds the value of the handle before it is
777   detached.  If the handle is already detached or closed, this will return
778   zero.
779
780   After calling this function, the handle is effectively invalidated, but the
781   handle is not closed.  You would call this function when you need the
782   underlying Win32 handle to exist beyond the lifetime of the handle object.
783
784   .. audit-event:: winreg.PyHKEY.Detach key winreg.PyHKEY.Detach
785
786
787.. method:: PyHKEY.__enter__()
788            PyHKEY.__exit__(*exc_info)
789
790   The HKEY object implements :meth:`~object.__enter__` and
791   :meth:`~object.__exit__` and thus supports the context protocol for the
792   :keyword:`with` statement::
793
794      with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
795          ...  # work with key
796
797   will automatically close *key* when control leaves the :keyword:`with` block.
798
799
800